2가지 방법으로 문제를 풀었다.
/*
문제
Implement a function called, areThereDuplicates
which accepts a variable number of arguments,
and checks whether there are any duplicates among
the arguments passed in.
You can solve this using the frequency counter pattern
OR the multiple pointers pattern.
Restrictions:
Time - O(N)
Space - O(N)
Bonus:
Time - O(Nlog(N))
Space - O(1)
*/
// 1. 자바스크립트 object 이용
function areThereDuplicates(...args) {
let obj = {};
for (let i = 0; i < args.length; i++) {
if (!obj[args[i]]) {
obj[args[i]] = 1;
} else {
return true;
}
}
return false;
}
console.log(areThereDuplicates(1, 2, 3)); // false
console.log(areThereDuplicates(1, 2, 2)); // true
console.log(areThereDuplicates('a', 'b', 'c', 'd')); // false
// 2. Set 이용
function areThereDuplicates_(...args) {
let set = new Set(args);
return set.size !== args.length;
}
console.log(areThereDuplicates_(1, 2, 3)); // false
console.log(areThereDuplicates_(1, 2, 2)); // true
console.log(areThereDuplicates_('a', 'b', 'c', 'd')); // false