天天看點

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

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

思路:

統計數組中數字出現的次數是否獨一無二,有兩部分需要做:

1.統計各數字出現的次數

2.看個數字出現次數是否有相同的

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        Map map2 = new HashMap<Integer, Integer>();
		int value = 0;
        for ( int i = 0; i < arr.length; i++ ) {
            if ( map.containsKey(arr[i]) ) {
                value = (int)map.get(arr[i]);
                value++;
                map.put(arr[i], value);
            }else {
                map.put(arr[i], 1);
            }
        }
        for ( Map.Entry<Integer, Integer> entry : map.entrySet() ) {
            if ( map2.containsKey(entry.getValue())) {
                return false;
            }else {
                map2.put(entry.getValue(), 0);
            }
        }
        return true;
    }
}