넘치게 채우기

[LeetCode] 1207. Unique Number of Occurrences 본문

PS/LeetCode

[LeetCode] 1207. Unique Number of Occurrences

riveroverflow 2024. 1. 17. 10:15
728x90
반응형

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

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

leetcode - Unique Number of Occurrences

문제 유형 : 해시

문제 난이도 : 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.

 

정수 배열 arr이 주어진다. 만약 각 숫자별 빈도가 중복되지 않는다면 true를, 아니면 false를 반환하라.

 

 

풀이

빈도를 저장하기 위해서 map을 만든다.

배열을 한 번 순회하며 빈도를 저장한다.

 

각각의 빈도를 확인하며, 빈도 리스트에 저장한다.

만약 빈도값이 기존에 있는 것이라면, false를 반환한다.

모든 map을 순회하고도 무사하다면 true를 반환한다.

 

 

코드

C++

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        unordered_map<int, int> occ;
        for(const auto &num : arr) {
            occ[num]++;
        }

        set<int> st;
        for(const auto & o : occ) {
            if(st.find(o.second) != st.end()) return false;
            st.insert(o.second);
        }

        return true;
    }
};

 

728x90
반응형