난이도 : medium
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
var findDuplicates = function(nums) {
let resultArr = [];
let resultObj = {};
for(let i=0; i < nums.length; i++){
if ( nums[i] in resultObj ) {
resultObj[nums[i]]++;
} else {
resultObj[nums[i]] = 1;
}
}
for (let key in resultObj){
if(resultObj[key] === 2){
resultArr.push(key);
}
}
return resultArr;
};
new Set을 객체로 활용해서 풀어낸 방식 ..감탄쓰
var findDuplicates = function(nums) {
const set = new Set(nums);
nums.forEach(n => {
if (set.has(n)) {
set.delete(n);
} else {
set.add(n);
}
})
return Array.from(set);
};