void topdown(map<int,int> &m,vector<int> &heap,int size,int r) { int tmp=heap[r]; int i; for(i=r;i*2+1<size;) { int j=i*2+1; if(j<size-1&&m[heap[j]]<m[heap[j+1]]) j++; if(m[tmp]<m[heap[j]]) { heap[i]=heap[j]; i=j; } else { break; } } heap[i]=tmp; } vector<int> topKFrequent(vector<int>& nums, int k) { map<int,int> m; int len=nums.size(); vector<int> heap; for(int i=0;i<len;i++) { m[nums[i]]++; if(m[nums[i]]==1) heap.push_back(nums[i]); } int s=heap.size(); for(int i=s/2-1;i>=0;i--) { topdown(m,heap,s,i); } for(int i=0;i<k;i++) { int tmp=heap[0]; heap[0]=heap[s-1-i]; heap[s-1-i]=tmp; topdown(m,heap,s-i-1,0); } vector<int> res(k); for(int i=0;i<k;i++) res[i]=heap[s-i-1]; return res; }
来源:https://www.cnblogs.com/QingFengDaHui/p/12387789.html