본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1207. Unique Number of Occurrences

반응형

https://leetcode.com/problems/unique-number-of-occurrences/

 

Unique Number of Occurrences - LeetCode

Can you solve this real interview question? 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: tr

leetcode.com

자료구조를 이용한 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

빈도수를 저장할 freqMap과 빈도수의 고유성을 저장할 uniqueMap을 선언해줍니다.

📔 풀이과정

1. arr에 대해 원소를 순회하며 freqMap에 빈도수를 저장해줍니다.

2. freqMap의 원소를 수행하며 uniqueMap에 freqMap의 second가 존재한다면 빈도수가 고유하지 않으므로 바로 false를 반환합니다.

📔 정답 출력 | 반환

true를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        map <int ,int> freqMap, uniqueMap;

        for(auto a : arr) {
            freqMap[a]++;
        }
        
        for(auto el : freqMap) {
            if(uniqueMap[el.second]) return false;
            uniqueMap[el.second] = 1;
        }

        return true;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.