面试题:最小的K个数

题目描述:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

方法1:排序

方法2:分割

import java.util.*;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> result = new ArrayList<>();
        if(input.length < k || input == null || k <= 0){
            return result;
        }
        int start = 0;
        int end = input.length - 1;
        int index = partition(input,start,end);
        while(index != k-1){
            if(index>k-1){
                end = index - 1;
                index = partition(input,start,end);
            }else{
                start = index + 1;
                index = partition(input,start,end);
            }
        }
        for(int i=0;i<=index;i++){
            result.add(input[i]);
        }
        return result;
    }
    public int partition(int[] input,int start,int end){
        int temp = input[start];
        while(start < end){
            while(start<end&&temp<=input[end]){
                --end;
            }
            input[start] = input[end];
            while(start<end&&input[start]<temp){
                ++start;
            }
            input[end] = input[start];
        }
        input[start] = temp;
        return start;
    }
}

方法3:堆排序

原文地址:https://www.cnblogs.com/Aaron12/p/9511894.html