一、解法一:快排 O(n)的算法,只有当我们可以修改输入的数组时可用
import java.util.ArrayList;
public class Solution {public ArrayList GetLeastNumbers_Solution(int [] input, int k) {
ArrayList aList = new ArrayList();
if(input.length == 0 || k > input.length || k <= 0)
return aList;
int low = 0;
int high = input.length-1;
int index = Partition(input,low,high);
while(index != k-1){
if (index > k-1) {
high = index-1;
index = Partition(input,low,high);
}else{
low = index+1;
index = Partition(input,low,high);
}
}
for (int i = 0; i < k; i++)
aList.add(input[i]);
return aList;
}
public int Partition(int array[],int start,int end){
int pivotkey=(int)start+(int)Math.random()*(end-start);
while(start<end){
while(start<end&&array[end]>=array[pivotkey])
end--;
swap(array,start,end);
while(start<end&&array[start]<=array[pivotkey])
start++;
swap(array,start,end);//这两段顺序不可改变
}
return start;
}
private void swap(int[] input, int low, int high) {
int temp = input[high];
input[high] = input[low];
input[low] = temp;
}
}
二:O(nlogk)的算法,特别适合处理海量数据
堆排序
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(k <= 0 || k > input.length)
return list;
heapSort( input, k, list);
return list;
}
private void swap(int[] arr, int m, int n){
int temp = arr[m];
arr[m] = arr[n];
arr[n] = temp;
}
private void heapSort(int[] arr, int k, ArrayList<Integer> list){
int len = arr.length;
for(int i = len/2 - 1; i >= 0; i--){
heapAdjust(arr, i, len - 1);
}
for(int i = len - 1; i >= len - k; i--){
list.add(arr[0]);
swap(arr, 0, i);
heapAdjust(arr, 0, i - 1);
}
}
private void heapAdjust(int[] arr, int index, int len){
int temp = arr[index];
for(int i = 2 * index + 1; i <= len; i = i * 2 + 1){
if(i < len && arr[i] > arr[i + 1]){
i++;
}
if(arr[i] >= temp)
break;
arr[index] = arr[i];
index = i;
}
arr[index] = temp;
}
}