快排学习(LeetCode 215题)

给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
提示:
1 <= k <= nums.length <= 104
-104 <= nums[i] <= 104

思路1:采用优先级队列的办法,当队列长度大于 k 时,进行出队。当遍历过所有的数字后,对顶即为第 k 个最大的元素。
class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        for(int num : nums){
            heap.offer(num);
            if(heap.size() > k){
                heap.poll();
            }
        }
        return heap.peek();
    }
}
思路2:采用快排的办法。函数 partition 中的变量 first 作为指针1,始终指向最后一个比基准值小的值,循环中的 i 作为第二个指针,当发现有数字比基准值小,则 first 右移一次,交换指针 first 和 i 指向的值。最后再把 first++,进行交换,使得基准值左侧都比基准值小,右侧都比基准值大。
class Solution {
    public int findKthLargest(int[] nums, int k) {
       int len = nums.length - 1;
       int target = len - k + 1;
       int start = 0,end = len;
       int index = partition(nums,start,end);
       while(index != target){
           if(index < target){
               start = index + 1;
           }else{
               end = index - 1;
           }
           index = partition(nums,start,end);
       }
       return nums[target];
    }
    public int partition(int[] nums,int start,int end){
        Random random = new Random();
        int pivot = random.nextInt(end - start + 1) + start;
        int first = start - 1;
        swap(nums,pivot,end);
        for(int i = start ; i < end; i++){
            if(nums[i] < nums[end]){
                first++;
                swap(nums,first,i);
            }
        }
        first++;
        swap(nums,end,first);
        return first;
    }
    public void swap(int[] nums,int i,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值