[LeetCode] Unique Number of Occurrences
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
Constraints:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
여러 개의 숫자가 들어간 배열이 주어진다.
그 안에 같은 숫자가 포함되어 있을 수 있는데, 각 숫자별 배열 내에 존재하는 수가 모두 달라야 한다.
var uniqueOccurrences = function(arr) {
const numSet = new Set(arr);
const numObj = {};
for(const num of numSet){
numObj[num] = 0
}
for(const num of arr){
numObj[num]++;
}
return new Set(Object.values(numObj)).size === numSet.size;
};
그래서 우선 set으로 만들어서 그걸로 각 숫자가 나타나는 수를 저장할 객체를 만들고,
한 번 반복문을 돌아서 동일한 숫자가 나타날 때마다 +1을 해준다.
그 후에 해당 객체의 값들을 set으로 만들어서 사이즈를 비교하면 끝~.~
지금 보니 굳이 set으로 해서 객체를 만들어줄 필요까진 없었다 싶다ㅋㅋㅋ
그거랑 별개로 주어진 arr의 길이가 1이면 그냥 바로 true 리턴해도 되고~.~
'코테연습' 카테고리의 다른 글
[LeetCode] Determine if Two Strings Are Close (0) | 2025.04.28 |
---|---|
[LeetCode] Find the Difference of Two Arrays (0) | 2025.04.23 |
[LeetCode] Find Pivot Index (0) | 2025.04.22 |