跳至主要內容

217. Contains Duplicate


217. Contains Duplicateopen in new window

🟢   🔖  数组 哈希表 排序  🔗 LeetCodeopen in new window

题目

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1]

Output: true

Example 2:

Input: nums = [1,2,3,4]

Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]

Output: true

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

题目大意

如果数组里面有重复数字就输出 true ,否则输出 flase

解题思路

map 判断即可。

代码

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function (nums) {
	const map = new Map();
	for (let item of nums) {
		if (map.has(item)) return true;
		map.set(item, 1);
	}
	return false;
};

相关题目

相关题目
- [219. 存在重复元素 II](./0219.md)
- [220. 存在重复元素 III](https://leetcode.com/problems/contains-duplicate-iii)
- [2357. 使数组中所有元素都等于零](https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts)