剑指offer -- 最小的k个数

题目描述

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

AC代码1

利用快速排序的思想找到第k - 1位置的数字。
缺点:改动了原数组。

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> resList = new ArrayList<>();
        //必须保证k <= input.length
        if(input == null || input.length == 0 || k <= 0 || k > input.length) return resList;
        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 < k;i++) resList.add(input[i]);
        return resList;
    }
    
    private int partition(int[] array, int start, int end){
        int temp = array[start];
        int low = start;
        int high = end;
        while(low < high){
            while(high > low && array[high] >= temp) high--;
            if(low < high) array[low] = array[high];
            while(high > low && array[low] <= temp) low++;
            if(low < high) array[high] = array[low];
        }
        array[low]= temp;
        return low;
    }
}

方法2

利用最大堆。

你可能感兴趣的:(算法,剑指offer)