(java)求个数最多的前K个数

题目:

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.
Subscribe to see which companies asked this question

代码如下:

<span style="font-size:24px;">public class Solution {
    	public static List<Integer> topKFrequent(int[] nums, int k) {
       List<Integer> r=new ArrayList<Integer>();
		Arrays.sort(nums);
        TreeSet<Number> set=new TreeSet<Number>(new Compare());
        int temp=nums[0];
        int count=1;
        for(int i=1;i<nums.length;i++){
        	if(nums[i]==temp){
        		count++;
        	}else{
        		Number n=new Number(temp,count);
        		set.add(n);
        		temp=nums[i];
        		count=1;
        	}
        }
        Number n=new Number(temp,count);
		set.add(n);
		Iterator<Number> it=set.iterator();
		int i=0;
		while(it.hasNext() && i<k){
		    i++;
			r.add(it.next().n);
		}
		return r;
    }
}
class Number{
	int n;
	int count;
	public Number(int x,int y){
		n=x;
		count=y;
	}
}
class Compare implements Comparator<Number>{
	public int compare(Number n1,Number n2){
		if(n2.count>n1.count){
			return 1;
		}else{
			return -1;
		}
	}
}</span>

注意的是:

TreeSet按照对象的属性排序的时候,实现CompareTo排序的时候或者是按照1和-1 两种情况,如果加上==则会出现去掉相同数值的对象??????

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值