题目描述
难度级别:简单
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
解题思路
哈希表
遍历数组元素,将数组元素存入哈希表中,若元素已在哈希表中输出true。
const containsDuplicate = function(nums) {
const hashMap = new Map()
for (let i = 0; i < nums.length; i++) {
if (!hashMap.has(nums[i]))
hashMap.set(nums[i], i)
else
return true
}
return false
};
排序
将数组排序后,若存在相同值则必然是连着的。
const containsDuplicate = function(nums) {
nums.sort()
for (let i = 0; i < nums.length; i++)
if (nums[i] === nums[i+1]) return true
return false
};
集合Set
通过集合去重数组,比较2者元素的数量。
const containsDuplicate = nums =>
new Set(nums).size !== nums.length
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate
网友评论