即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

LeetCode 347. Top K Frequent Elements

编程语言 Lutte_ 29℃ 0评论

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.

public class Solution {
    public List topKFrequent(int[] nums, int k) {
        int n = nums.length;
        List[] bucket = new List[n+1];
        List list = new ArrayList<>();
        Map map = new HashMap<>();
        for(int i =0 ;i ();
            }
            bucket[temp].add(key);
        }
        for(int i = bucket.length -1 ; i>=0 && list.size() < k; i--) {
            if(bucket[i]!=null) {
                list.addAll(bucket[i]);
            }
        }
        return list;
    }
}





转载请注明:CodingBlog » LeetCode 347. Top K Frequent Elements

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情