您的位置:首页 > 产品设计 > UI/UE

347-m-Top K Frequent Elements

2016-05-14 16:48 441 查看
求一个数组中出现频率排名前k的数字。(搜了下其他解法,大多用的都是c++的stl,stl是方便,不像纯c要自建哈希表还要手动排序)

一定要理解好题目,求的是出现频率排名前k,而不是出现频率大于等于k,即如果k=2,那么[1,1,1,2,2,2,3,3]所求为出现频率最高的2个数字,结果为[1,2],而不是[1,2,3]。开始我理解为>=k,解出结果是错的。

leet上类似的题目不少了一看就是要哈希。我的大体解法也是哈希,但因为求的是最大的前k个,所以哈希后还要对哈希表中的结果排序,于是构造的哈希表为数组的数组,存的是nums[i]出现的次数x和i(即对应原数组中的下标),然后根据x快速排序,输出后k个元素。由于数字有正有负,所以还要构造个哈希表存负数。虽然ac了,但觉得写得不好很臃肿。

如下:

void sortKFrequent(int **nums, int numsSize, int low, int high) {
if (low > high)
return;

int l = low, h = high;
int target = nums[low][1];

int *tempNode = NULL;
while (l < h) {
while (l < h && target < nums[h][1])
h--;
tempNode = nums[l];
nums[l] = nums[h];
nums[h] = tempNode;
//        swapPointer(&nums[l], &nums[h]);

while (l < h && target >= nums[l][1])
l++;
tempNode = nums[h];
nums[h] = nums[l];
nums[l] = tempNode;
//        swapPointer(&nums[l], &nums[h]);
}

sortKFrequent(nums, numsSize, low, l - 1);
sortKFrequent(nums, numsSize, l + 1, high);
}
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
int *result = (int *)malloc(sizeof(int) * k);
memset(result, 0, sizeof(int) * k);
*returnSize = 0;

int n = 10240;
int **tablePostive = (int **)malloc(sizeof(int *) * n);
int **tableNegative = (int **)malloc(sizeof(int *) * n);
memset(tablePostive, 0, sizeof(int) * n);
memset(tableNegative, 0, sizeof(int) * n);
for (int i = 0; i < n; i++) {
tablePostive[i] = (int *)malloc(sizeof(int) * 2);
tableNegative[i] = (int *)malloc(sizeof(int) * 2);
}

int pmini = 1024, nmini = 1024;
int pmax = 0, nmax = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] >= 0) {
tablePostive[nums[i]][0] = nums[i];
tablePostive[nums[i]][1]++;

if (pmax <= nums[i])
pmax = nums[i];
if (pmini >= nums[i])
pmini = nums[i];
}
else {
tableNegative[-nums[i]][0] = nums[i];
tableNegative[-nums[i]][1]++;

if (nmax <= -nums[i])
nmax = -nums[i];
if (nmini >= -nums[i])
nmini = -nums[i];
}
}

if (pmax)
sortKFrequent(tablePostive, pmax, pmini, pmax);
if (nmax)
sortKFrequent(tableNegative, nmax, nmini, nmax);

while (k > 0) {
if (tablePostive[pmax][1] >= tableNegative[nmax][1]) {
result[*returnSize] = tablePostive[pmax][0];
*returnSize += 1, pmax--;
}
else if (tablePostive[pmax][1] < tableNegative[nmax][1]) {
result[*returnSize] = tableNegative[nmax][0];
*returnSize += 1, nmax--;
}
else {
;
//            result[*returnSize] = tablePostive[pmax][0];
//            *returnSize += 1, pmax--;
//
//            result[*returnSize] = tableNegative[nmax][0];
//            *returnSize += 1, nmax--;
}

k--;
}

free(tablePostive);
free(tableNegative);

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode