TopM实现

/**
 * 求最大的M个  解决方案:小根堆(数据量比较大的情况下
 * @author 团团儿
 *
 */
public class TopM {
	/**
	 * 创建k个节点的小根堆
	 */
	public int[] createHeap(int a[],int k) {
		int[] result=new int[k];
		for (int i = 0; i <k; i++) {
			result[i]=a[i];
		}
		for (int i = 1; i < k; i++) {
			int child=i;
			int parent=(i-1)/2;
			while (child!=0&&parent>=0&&result[parent]>result[child]) {
				int temp=result[child];
				result[child]=result[parent];
				result[parent]=temp;
				child=parent;
				parent=(parent-1)/2;
			}
		}
		return result;
	}
	/**
	 * 插入新值
	 * @param result
	 * @param value
	 */
	public  void insertHeap(int result[],int value) {
		result[0]=value;
		int parent=0;
		while (parent<result.length) {
			int lchild=parent*2+1;
			int rchild=parent*2+2;
			int minIndex=parent;//指向左右儿子中最小的
			if(lchild<result.length&&result[lchild]<result[parent])
				minIndex=lchild;
			if(rchild<result.length&&result[rchild]<result[minIndex])
				minIndex=rchild;
			if (minIndex==parent) {
				break;
			}else {
				int temp=result[minIndex];
				result[minIndex]=result[parent];
				result[parent]=temp;
				parent=minIndex;
			}
		}
	}
	/**
	 * 找到前k个最大值
	 * @param a
	 * @param k
	 * @return
	 */
	public int[] getTopByHeap(int a[],int k) {
		int result[]=createHeap(a, k);
		for (int i = k; i <a.length; i++) {
			if (a[i]>result[0]) {
				insertHeap(result, a[i]);
			}
		}
		return result;
	}
	public static void main(String[] args) {  
        int a[] = {4,3,5,1,2,8,9,10};//待找TOP M 的排海量数据N  
        int result[] = new TopM().getTopByHeap(a, 6);  
        System.out.print("TOP M is :");  
        for(int resultItem : result) {  
            System.out.print(resultItem + "   ");  
        }  
    }  
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值