题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
import java.util.ArrayList; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { ArrayList<Integer> list = new ArrayList<>(); if(k>input.length || k<=0)return list; findKthSmallest(input, k); for(int i = 0; i < k; i++) { list.add(input[i]); } return list; } public void findKthSmallest(int[] input, int k) { int l = 0; int r = input.length-1; while(l<r) { int j = partition(input, l , r); if(j == k) break; else if(j < k) l = j+1; else r = j-1; } } public int partition(int[] input, int start, int end) { int p = start-1; int i = start; for(; i < end; i++) { if(input[i]<input[end]) { p=p+1; swap(input, p, i); } } p=p+1; swap(input, p, end); return p; } public void swap(int[] input, int i, int j) { int temp = input[i]; input[i] = input[j]; input[j] = temp; } }