求一个数组中最小的K个数字

用快排思想:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
 
class Solution 
{
	public void solve(ArrayList<Integer> res,int[] input,int left,int right,int k)
	{
		int t;
		int i=left;
		int j=right;
		int temp=input[left];
		while(i<j)
		{
			i=i+1;
			while(input[i]<temp&&i<right)
				i++;
			while(input[j]>temp&&j>left)
				j--;
			if(i<j)
			{
				t=input[i];
				input[i]=input[j];
				input[j]=t;
			}
		}
		if(j>=left&&i<=right)
		{
			t=input[left];
			input[left]=input[j];
			input[j]=t;
		}
		if(j+1==k)
		{
			for(int u=0;u<k;u++)
				res.add(input[u]);
			return;
		}
		if(j+1>k&&j>left)
			solve(res,input,left,j-1,k);
		if(j+1<k&&i <right)
			solve(res,input,j+1,right,k);
	}
    public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k)
    {
    	ArrayList<Integer> res=new ArrayList<Integer>();
    	if(input.length==k)
    		for(int i=0;i<input.length;i++)
    			res.add(input[i]);
    	else if(input.length!=0)
    		solve(res,input,0,input.length-1,k);
    	return res;
    	
    }
}

用最大堆保存这k个数,每次只和堆顶比,如果比堆顶小,删除堆顶,新数入堆。

import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
   public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
       ArrayList<Integer> result = new ArrayList<Integer>();
       int length = input.length;
       if(k > length || k == 0){
           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 temp = maxHeap.poll();
                temp = null;
                maxHeap.offer(input[i]);
            }
        }
        for (Integer integer : maxHeap) {
            result.add(integer);
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/yanhanwen123/article/details/80145434