码迷,mamicode.com
首页 > 其他好文 > 详细

347. Top K Frequent Elements

时间:2016-09-15 06:27:16      阅读:188      评论:0      收藏: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.

 

 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

标签:

原文地址:http://www.cnblogs.com/renyualbert/p/5874218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!