347. Top K Frequent Elements

Posted 咖啡中不塌缩的方糖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 ];
    }

 

 

以上是关于347. Top K Frequent Elements的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements