一、題目描述
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。
二、題目分析
- 典型的排序題目,直接使用-快速排序
- 注意一下,input數組的空值和input.length的值與K值的比較
三、題目代碼
package offer;
import java.util.ArrayList;
/*
* 最小K個數
*/
public class Test28 {
static ArrayList<Integer> list = new ArrayList<Integer>();
public static void main(String[] args) {
Test28 test28 = new Test28();
int[] input = new int[] { 4, 5, 1, 6, 2, 7, 3, 8 };
list = test28.GetLeastNumbers_Solution(input, 4);
System.out.println(list);
}
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
if (input.length == 0 || input.length < k) {
return list;
}
sort(input, 0, input.length - 1);
for (int i = 0; i < k; i++) {
list.add(input[i]);
}
return list;
}
void sort(int[] input, int start, int end) {
if (start > end) {
return;
}
int i = start;
int j = end;
int key = input[i];
while (i < j) {
while (i < j && input[j] >= key) {
j--;
}
input[i] = input[j];
while (i < j && input[i] <= key) {
i++;
}
input[j] = input[i];
}
input[i] = key;
sort(input, start, i - 1);
sort(input, i + 1, end);
}
}