给你一个整数数组 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
方法一:哈希表 首先使用哈希表记录每个数字的出现次数;随后再利用新的哈希表,统计不同的出现次数的数目。如果不同的出现次数的数目等于不同数字的数目,则返回 true,否则返回 false。
[sol1-C++] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution {public : bool uniqueOccurrences (vector<int >& arr) { unordered_map<int , int > occur; for (const auto & x: arr) { occur[x]++; } unordered_set<int > times; for (const auto & x: occur) { times.insert (x.second); } return times.size () == occur.size (); } };
[sol1-Java] 1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution { public boolean uniqueOccurrences (int [] arr) { Map<Integer, Integer> occur = new HashMap <Integer, Integer>(); for (int x : arr) { occur.put(x, occur.getOrDefault(x, 0 ) + 1 ); } Set<Integer> times = new HashSet <Integer>(); for (Map.Entry<Integer, Integer> x : occur.entrySet()) { times.add(x.getValue()); } return times.size() == occur.size(); } }
[sol1-C] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 struct unordered_set { int key; UT_hash_handle hh; }; struct unordered_map { int key; int val; UT_hash_handle hh; }; bool uniqueOccurrences (int * arr, int arrSize) { struct unordered_map * occur = NULL ; for (int i = 0 ; i < arrSize; i++) { struct unordered_map * tmp = NULL ; HASH_FIND_INT(occur, &arr[i], tmp); if (tmp == NULL ) { tmp = malloc (sizeof (struct unordered_map )); tmp->key = arr[i], tmp->val = 1 ; HASH_ADD_INT(occur, key, tmp); } else { (tmp->val)++; } } struct unordered_set * times = NULL ; struct unordered_map *cur , *cur_tmp ; HASH_ITER(hh, occur, cur, cur_tmp) { struct unordered_set * tmp = NULL ; HASH_FIND_INT(times, &(cur->val), tmp); if (tmp == NULL ) { tmp = malloc (sizeof (struct unordered_set )); tmp->key = cur->val; HASH_ADD_INT(times, key, tmp); } } return HASH_COUNT(occur) == HASH_COUNT(times); }
[sol1-JavaScript] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var uniqueOccurrences = function (arr ) { const occur = new Map (); for (const x of arr) { if (occur.has (x)) { occur.set (x, occur.get (x) + 1 ); } else { occur.set (x, 1 ); } } const times = new Set (); for (const [key, value] of occur) { times.add (value); } return times.size === occur.size ; };
[sol1-Golang] 1 2 3 4 5 6 7 8 9 10 11 func uniqueOccurrences (arr []int ) bool { cnts := map [int ]int {} for _, v := range arr { cnts[v]++ } times := map [int ]struct {}{} for _, c := range cnts { times[c] = struct {}{} } return len (times) == len (cnts) }
复杂度分析