zoukankan      html  css  js  c++  java
  • LeetCode-347. Top K Frequent Elements

    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;
        }

    桶排序

    堆排序

      

  • 相关阅读:
    GIT学习实践笔记
    ubuntu 安装pygit2
    强化vim打造python的IDE
    Python Django学习和实践
    浏览器调试工具网页性能分析中的使用
    公司发版shell脚本重构
    Nightwatch+gulp
    Git
    JavaScript Unit Test with Qunit
    Unit Test Mocking Framework
  • 原文地址:https://www.cnblogs.com/zhacai/p/10436261.html
Copyright © 2011-2022 走看看