最小k个树

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

 

解法一:使用Parttition函数

解法二:使用最大堆,一、在k个整数中找到最大数,二、有可能在这个容器中删除最大数,三、有可能插入一个新数

Java使用PriorityQueue优先队列来建堆

解法一

private int Partition(int[] input, int begin, int end) {
		int pivot=input[begin];
		while(begin<end){
			while(input[end]>=pivot &&begin<end)end--;
			input[begin]=input[end];
			while(input[begin]<=pivot&&begin<end)begin++;
			input[end]=input[begin];
		}
		input[begin]=pivot;
		return begin;
	}
    public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
		ArrayList<Integer>arrayList=new ArrayList<>();
		if(k<=0 ||input.length==0||k>input.length)return arrayList;
		int begin=0;
		int end=input.length-1;
		int index=Partition(input, begin, end);
		while(index!=k-1){
			if(index>k-1){
				end=index-1;
				index =Partition(input, begin, end);
			}
			else{
				begin=index+1;
				index=Partition(input, begin, end);
			}
		}
		for(int i=0;i<k;i++){
			arrayList.add((Integer)input[i]);
		}
		return arrayList;

解法二:

public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
		ArrayList<Integer>result=new ArrayList<Integer>();
		int length=input.length;
		if(k==0 ||k>length)return result;
		//最大堆
		PriorityQueue<Integer>maxHeap=new PriorityQueue<Integer>(k,new Comparator<Integer>() {
			@Override
			public int compare(Integer o1,Integer o2){
				return o2.compareTo(o1);
			}
		});
		for(int i=0;i<length;i++){
			if(maxHeap.size()!=k){
				maxHeap.offer(input[i]);
			}else if(maxHeap.peek()>input[i]){
				Integer tmp=maxHeap.poll();
				tmp=null;
				maxHeap.offer(input[i]);
			}
		}
		for(Integer integer:maxHeap){
			result.add(integer);
		}
		return result;
		
		
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值