One question per day Leetcode1207 unique occurrences

Leetcode1207 unique number of appearances

Title description:

Give you an integer array arr, please help count the number of occurrences of each number in the array.
If the number of occurrences of each number is unique, return true; otherwise, return false.

Example 1:

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: In the array, 1 appears 3 times, 2 appears 2 times, and 3 only appears once. No two numbers have the same number of occurrences.

Example 2:

Input: arr = [1,2]
Output: false

Example three:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

answer:

The idea of ​​this question is very simple. First, a hash table map is needed to count the number of occurrences of each integer, and then a hash table set is opened to store the total number of occurrences. If the number of different integers is equal to the number of different occurrences, return true, otherwise return false.
For example 1, the calculated map is as follows:
1:3
2:2
3:1
The number of different integers is 3, and the three different integers
are
1, 2, and 3. The statistical set is as follows: 1 2 3
The number of different occurrences Is also 3, so return true

AC code

class Solution {
    
    
public:
    bool uniqueOccurrences(vector<int>& arr) {
    
    
        unordered_map<int, int> m;
        unordered_set<int> s;
        for(int num : arr)
            m[num]++;
        for(auto m_n : m)
            s.insert(m_n.second);
        return s.size() == m.size();
    }
};

Welcome to reprint, indicate the source.

Question source: LeetCode
Link: https://leetcode-cn.com/problems/unique-number-of-occurrences/

Guess you like

Origin blog.csdn.net/qq_36583373/article/details/109331659