这个题可以用快速排序,但是不用完全排序完毕。只需要排序K之前的元素即可。


public class Solution {
    int k;
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        this.k = k;
        quickSort(input,0,input.length-1);
         ArrayList<Integer> list = new ArrayList<>();
        for(int i=0;i<k;++i){
            list.add(input[i]);
        }
        return list;
    }
    public void quickSort(int[] nums,int low,int high){
        if(low<high){
            int mid = partion(nums,low,high);
            if(mid>k){
                quickSort(nums,low,mid-1);
            }
            else {
                quickSort(nums,low,mid-1);
                quickSort(nums,mid+1,high);
            }
            
        }
    }
    public int partion(int[] nums,int low,int high){
        int pivot = nums[low];
        while(low<high){
            while(low<high&&pivot<=nums[high])--high;
            nums[low] = nums[high];
            while(low<high&&pivot>=nums[low])++low;
            nums[high] = nums[low];
            nums[low] = pivot;
        }
        return low;
    }
}