문제
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
풀이
집합을 하나 만들고, 배열의 원소들을 집합에 계속 추가해나가면서 검사함. 집합에 nums의 엘리먼트를 추가한 직후에 집합의 길이와 현재 인덱스가 일치하지 않는다는건 집합에 중복이 발생했다는 의미이므로 true를 리턴한다. nums배열이 빈배열인 경우에는 for문이 돌지 않기 떄문에 false가 리턴되고, 원소가 딱 하나 있는 경우에는 집합의 길이와 인덱스 번호가 같아질일이 없다. 그래서 예외처리를 따로 안해줘도 된다.
var containsDuplicate = function(nums) {
const set = new Set();
for (let i = 0; i < nums.length; i++) {
set.add(nums[i]);
if (i === set.size) return true;
}
return false;
};