Difficulty:medium
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
解题思路:
题目要求时间复杂度为O(n log n),如果采用k次遍历n次双重循环得到最大的数字就会导致产生额外的时间,直接提交就会出现超时
选择比较快捷的方法应该是采用新开数组存贮每一个数字所对应的个数,例如对于数字1,arr[1]=3;对于数字3,arr[3]=1这样就可以将多个相同数字的存储简化为单个数字的存贮量,方便之后遍历查找k个最大的数字。但是对于数字的角标只能为整数,所以需要新开出2个数组,一个数组存贮正数,另外一个数组存贮负数取绝对值后的数值,这样就可以区分。
之后利用遍历整个数组的大小,在两个数组中挑出最大的一个数值,记录角标,并且通过judge变量记录是从两个正负数组中那个里面得到的数值,并且在取得数值之后需要将角标位置下arr[i]的值清零
代码如下:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int list1[50000]={0};
int list2[50000]={0};
vector<int> ans;
int n=nums.size();
for(int i=0;i<n;i++)
{
if(nums[i]>=0)list1[nums[i]]++;
else list2[nums[i]*-1]++;
}
for(int i=0;i<k;i++)
{
int max=0;
int index=0;
bool judge=0;
for(int j=0;j<50000;j++)
{
if(list1[j]>=list2[j])
{
if(list1[j]>max)
{judge=0;
max=list1[j];
index=j;
}
}
else if(list1[j]<list2[j])
{
if(list2[j]>max)
{judge=1;
max=list2[j];
index=j;
}
}
}
if(judge==0)
{
ans.push_back(index);
list1[index]=0;
}
else
{
ans.push_back(-index);
list2[index]=0;
}
}
return ans;
}
};