剑指offer(Java实现)40 - 最小的K个数

最小的K个数-40

输入n个整数,找出其中最小的k个数。

注意:

  • 数据保证k一定小于等于输入数组的长度;
  • 输出数组内元素请按从小到大顺序排序;
样例
输入:[1,2,3,4,5,6,7,8] , k=4
输出:[1,2,3,4]

思路:

partition

class Solution {
    public List<Integer> getLeastNumbers(int[] nums, int k) {
        List<Integer> res = new ArrayList<>();
        int left = 0, right = nums.length - 1;
        int mid = left + (right - left) / 2;
        int index = partition(nums, left, right);
        while (index != k - 1) {
            if (index > mid) index = partition(nums, left, index - 1);
            else if (index < mid) index = partition(nums, index + 1, right);
        }
        for (int i = 0; i < index; i++) res.add(nums[i]);
        return res;
    }

    private int partition(int[] nums, int left, int right) {
        int temp = nums[left];
        while (left < right) {
            while (left < right && nums[right] >= temp) right--;
            nums[left] = nums[right];
            while (left < right && nums[left] <= temp) left++;
            nums[right] = nums[left];
        }
        nums[left] = temp;
        return left;
    }
}

小根堆

class Solution {
    public List<Integer> getLeastNumbers_Solution(int [] input, int k) {
        List<Integer> res = new ArrayList<>();
        PriorityQueue<Integer> maxpq = new PriorityQueue<>();
        for(int num : input){
            maxpq.add(num);
        }
        for(int i = 0; i < k; i++){
            res.add(maxpq.poll());
        }
        return res;
    }
}

堆排序要复习一下了…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值