zoukankan      html  css  js  c++  java
  • 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.

     Using Count Sort

    public IList<int> TopKFrequent(int[] nums, int k) {
            var res = new List<int>();
            if(nums.Count()==0) return res;
            var hashtable = new Dictionary<int,int>();
            for(int i =0;i< nums.Count();i++)
            {
                if(hashtable.ContainsKey(nums[i])) hashtable[nums[i]]++;
                else hashtable.Add(nums[i],1);
            }
            //sort by count sort
            var dp = new List<int>();
            foreach(var pair in hashtable)
            {
                dp.Add(pair.Value);
            }
            int a = FindK(dp,k);
            foreach(var pair in hashtable)
            {
                if(pair.Value >= a) res.Add(pair.Key);
            }
            return res;
        }
        
        public int FindK (List<int> nums, int k)
        {
            if(nums.Count()==0) return 0;
            int max = nums[0];
            int min = nums[0];
            var b = new int[nums.Count()];
            foreach(int n in nums)
            {
                max = Math.Max(max,n);
                min = Math.Min(min,n);
            }
            
            int kk = max - min +1;
            var c = new int[kk];
            for(int i =0;i<nums.Count() ;i++)
            {
                c[nums[i] - min] += 1;
            }
            for(int i =1;i<c.Count() ;i++)
            {
                c[i] = c[i] + c[i-1];
            }
            for(int i = nums.Count()-1; i >= 0; i--){
                b[--c[nums[i]-min]] = nums[i];
            }
            return b[nums.Count() - k ];
        }
     
  • 相关阅读:
    SpringBoot使用Swagger2实现Restful API
    SpringBoot返回json和xml
    SpringBoot定时任务
    SpringBoot+Jpa+MySql学习
    SpringBoot+Mybatis+MySql学习
    linux安装jdk
    linux下安装mysql
    利用nginx,腾讯云免费证书制作https
    SpringBoot使用数据库
    SpringBoot的国际化使用
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5874218.html
Copyright © 2011-2022 走看看