天天看點

LeetCode—— 1207 獨一無二的出現次數

問題描述

給你一個整數數組 

arr

,請你幫忙統計數組中每個數的出現次數。

如果每個數的出現次數都是獨一無二的,就傳回 

true

;否則傳回 

false

示例 1:

輸入:arr = [1,2,2,1,1,3]
輸出:true
解釋:在該數組中,1 出現了 3 次,2 出現了 2 次,3 隻出現了 1 次。沒有兩個數的出現次數相同。
示例 2:

輸入:arr = [1,2]
輸出:false
示例 3:

輸入:arr = [-3,0,1,-3,1,1,1,-3,10,0]
輸出:true
           

提示:

  • 1 <= arr.length <= 1000

  • -1000 <= arr[i] <= 1000

來源:力扣(LeetCode)

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

著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

執行結果

LeetCode—— 1207 獨一無二的出現次數

代碼描述

思路:先求鍵值對,再以次數為鍵,值設為1,一旦值不為1,則傳回false。

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        map<int, int> key_cnt;
        for(int i = 0; i < arr.size(); ++i)
        {
            key_cnt[arr[i]] += 1;
        }
        map<int, int> cnt_one;
        map<int, int>::iterator it = key_cnt.begin();
        for(; it != key_cnt.end(); ++it)
        {
            if(cnt_one.count(it->second)==0)
                cnt_one[it->second] = 1;
            else                
                return false;
        }
        return true;
    }
};
           

繼續閱讀