地址:
力扣
https://leetcode-cn.com/problems/unique-number-of-occurrences/
题目:
给你一个整数数组 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
首先想到了计数数组,这样可以统计每个数字出现的次数,然后依据次数进行排序,如果次数不相等,那么就不会出现连续的数字
另外一种方式是采用 hash map来实现统计数字出现次数,然后再统计“次数”的次数
方法一、计数数组
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
bool uniqueOccurrences(int* arr, int arrSize){
int cntArr[2001]={0};
bool ret = true;
int i;
for(i=0; i<arrSize; i++)
{
int idx = arr[i];
if(idx < 0)
{
idx = 0 - idx;
cntArr[idx]++;
}
else if(idx == 0)
cntArr[idx]++;
else
{
idx += 1000;
cntArr[idx]++;
}
}
qsort(cntArr, 2001, sizeof(int), cmp);
int tmp = 0;
for(i=0; i<2001; i++)
{
if(cntArr[i] != 0)
{
if(tmp == cntArr[i])
{
ret = false;
break;
}
tmp = cntArr[i];
}
}
return ret;
}
方法二、hash map
直接套用官网写法,因为 C 不提供 hash map 高级数据结构,但是目前有 uthash 帮我们完成了这个,关于这部分后续会开帖子介绍
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);
}
1050



被折叠的 条评论
为什么被折叠?



