首页 > 其他 > 详细

LeetCode-347. Top K Frequent Elements

时间:2019-02-26 13:25:26      阅读:180      评论:0      收藏:0      [点我收藏+]

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

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 List<Integer> topKFrequent(int[] nums, int k) {//排序 map my 
        List<Integer> res = new ArrayList<Integer>();
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }
            else{
                map.put(nums[i],1);
            }
        }
        for (int i = 0; i <k ; i++) {
            int max=0;
            int value = 0;
            for (Map.Entry entry:map.entrySet()) {
                if((Integer)entry.getValue()>max){
                    max = (Integer)entry.getValue();
                    value = (Integer)entry.getKey();
                }
            }
            res.add(value);
            map.put(value,0);
        }
        return res;
    }

桶排序

堆排序

  

 

LeetCode-347. Top K Frequent Elements

原文:https://www.cnblogs.com/zhacai/p/10436261.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!