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

LeetCode-Top K Frequent Elements

2016-08-11 12:40 399 查看
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

Analysis:

We can use bucket sort style solution: Since the largest frequency is N, we can use a size N array to store the element with each possible frequency.

Solution:

public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> res = new ArrayList<Integer>();
if (nums.length==0 || k==0) return res;

List<Integer>[] freqList = new List[nums.length+1];
Map<Integer,Integer> freqMap = new HashMap<Integer,Integer>();

// Get frequencey map
for (int num: nums){
freqMap.put(num,freqMap.getOrDefault(num,0)+1);
}

// According to each num's frequency, put it into frequency list
for (int num: freqMap.keySet()){
int freq = freqMap.get(num);
if (freqList[freq]==null){
freqList[freq] = new ArrayList<Integer>();
}
freqList[freq].add(num);
}

int left = k;
for (int i=freqList.length-1;i>=0 && left>0;i--){
if (freqList[i]!=null){
if (left>=freqList[i].size()){
res.addAll(freqList[i]);
left -= freqList[i].size();
} else {
for (int j=0;j<left;j++) res.add(freqList[i].get(j));
break;
}
}
}

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