347. Top K Frequent Elements

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.

一刷
题解:利用bucket sort的思路,先统计词频,然后再将frequency作为index访问得到具体的词。从大到小的前k个。

class Solution {
    public List topKFrequent(int[] nums, int k) {

    List[] bucket = new List[nums.length + 1];
    Map frequencyMap = new HashMap();

    for (int n : nums) {
        frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
    }

    for (int key : frequencyMap.keySet()) {
        int frequency = frequencyMap.get(key);
        if (bucket[frequency] == null) {
            bucket[frequency] = new ArrayList<>();
        }
        bucket[frequency].add(key);
    }

    List res = new ArrayList<>();

    for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
        if (bucket[pos] != null) {
            res.addAll(bucket[pos]);
        }
    }
    return res;
}
}

二刷

class Solution {
    public List topKFrequent(int[] nums, int k) {
        
        List result = new ArrayList();
        
        if (nums.length == 0 || nums.length == 1){
            if(k == 1){
                result.add(nums[0]);
            }
            
            return result;
        }
        
        PriorityQueue pq = new PriorityQueue(k,new NodeComparator());
        Arrays.sort(nums);
        
        int count = 1 ;
        for (int i = 1; i< nums.length;i++){
            if (nums[i] != nums[i-1]){
                pq.add(new Node(nums[i-1],count));
                count = 1;
            }else{
                count++;
            }
            
        }
        
        pq.add(new Node(nums[nums.length-1],count));
        
        count = 0; 
        while(count++{
    public int compare(Node a, Node b){
        if (a.count > b.count ){
            return -1;
        }else if (a.count < b.count){
            return 1;
        }else{
            return 0;
        }
    }
}

你可能感兴趣的:(347. Top K Frequent Elements)