coding test/leetCode

[leetCode/JS] 1207. Unique Number of Occurrences

쭘봉 2022. 11. 30. 14:05

난이도 [ 😊 ] Easy

 

문제 설명

Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.

 

int 로 이루어진 arr가 있다. 여기에 나오는 숫자가 발생횟수가 유니크 할때 true이다.

 

 

입출력 예

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.
1은 3번, 2는 2번, 3은 1번 나왔다. 각 숫자의 발생횟수가 1,2,3 번으로 중복되지 않으니 True이다.

 

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

 


 

내 솔루션

  • Object로 각 숫자를 key로 두고 발행 횟수를 value로 map을 셋팅한다.
  • Set에 넣어서 중복을 제거한 size와 sort의 length 비교하여 중복이 있는지 없는지 체크한다.

 

/**
 * @param {number[]} arr
 * @return {boolean}
 */
var uniqueOccurrences = function(arr) {
  const map = {}
  for(const a of arr){
    map[a] = (map[a] || 0) + 1;
  }
  const sort = Object.values(map)
  return new Set(sort).size === sort.length
};

 

감상평

  • 굉장히 심플! 첨엔 좀 느렸는데 최적화 계속해서 96%까지 올렸다.