最小的K个数

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

解题思路:方法一可以用类似patition的过程找到前k小的数,O(n)
还可以用最小堆来实现,O(nlogk)

import java.util.ArrayList;



public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(input == null || input.length <= 0 || k <= 0 || k > input.length) return res;
        int low = 0;
        int high = input.length-1;

        int index = Patition(input, k, 0, input.length-1);
        while(index != k-1){
            if(index > k-1){
                index = Patition(input, k, low, index-1);
            }else{
                index = Patition(input, k, index+1, high);
            }
        }
        for(int i = 0; i < k; i++){
            res.add(input[i]);
        }

        return res;
    }
    public int Patition(int[] input, int k, int low, int high){
        int pivot = input[k-1];
        swap(input, low, k-1);
        while(low < high){
            while(low < high && pivot <= input[high]){
                high--;
            }
            swap(input, low, high);
            while(low < high && pivot >= input[low]){
                low++;
            }
            swap(input, low, high);
        }
        return low;
    }
    public void swap(int[] input, int i, int j){
        int tmp = input[i];
        input[i] = input[j];
        input[j] = tmp;
    }
}

下面堆的实现做法来自牛客网。

import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
   public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
       ArrayList<Integer> result = new ArrayList<Integer>();
       int length = input.length;
       if(k > length || k == 0){
           return result;
       }
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        for (int i = 0; i < length; i++) {
            if (maxHeap.size() != k) {
                maxHeap.offer(input[i]);
            } else if (maxHeap.peek() > input[i]) {
                Integer temp = maxHeap.poll();
                temp = null;
                maxHeap.offer(input[i]);
            }
        }
        for (Integer integer : maxHeap) {
            result.add(integer);
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值