Easy difficulty · Question · Topics: arrays, set
Given an integer array nums, determine whether any element appears more than once.
Return true if at least one element occurs more than once; otherwise, return false.
Example 1
Input:
nums = [1, 2, 3, 3]
Output:
true
Explanation: The element 3 appears twice in the array.
Example 2
Input:
nums = [1, 2, 3, 4]
Output:
false
Explanation: Every element appears exactly once.
Example 3
Input:
nums = []
Output:
false
Explanation: An empty array contains no duplicate elements.
Use a Set to keep track of the elements encountered while traversing the array.
Set called seen.nums.seen, return true because a duplicate has been found.seen.false.class Solution {
/**
* @param {number[]} nums
* @return {boolean}
*/
hasDuplicate(nums) {
let set = new Set();
for(var i =0;i<nums.length;i++){
if(set.has(nums[i])) return true;
set.add(nums[i]);
}
return false;
}
}