【LeetCode-面试算法经典-Java实现】【215-Kth Largest Element in an Array(数组中第K大的数)】

126 篇文章 82 订阅

【215-Kth Largest Element in an Array(数组中第K大的数)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】


代码下载【https://github.com/Wang-Jun-Chao】

原题

  Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
  For example,
  Given [3,2,1,5,6,4] and k = 2, return 5.
  Note:
  You may assume k is always valid, 1 ≤ k ≤ array’s length.

题目大意

  从一个未经排序的数组中找出第k大的元素。注意是排序之后的第k大,而非第k个不重复的元素可以假设k一定是有效的, 1 ≤ k ≤ 数组长度

解题思路

  O(n)解法:快速选择(QuickSelect)算法

代码实现

算法实现类

import java.util.Collections;

public class Solution {

    public int findKthLargest(int[] nums, int k) {

        if (k < 1 || nums == null || nums.length < k) {
            throw new IllegalArgumentException();
        }

        return findKthLargest(nums, 0, nums.length - 1, k);
    }

    public int findKthLargest(int[] nums, int start, int end, int k) {

        // 中枢值
        int pivot = nums[start];
        int lo = start;
        int hi = end;

        while (lo < hi) {
            // 将小于中枢值的数移动到数组左边
            while (lo < hi && nums[hi] >= pivot) {
                hi--;
            }
            nums[lo] = nums[hi];

            // 将大于中枢值的数移动到数组右边
            while (lo < hi && nums[lo] <= pivot) {
                lo++;
            }
            nums[hi] = nums[lo];
        }

        nums[lo] = pivot;

        // 如果已经找到了
        if (end - lo + 1 == k) {
            return pivot;
        }
        // 第k大的数在lo位置的右边
        else if (end - lo + 1 > k){
            return findKthLargest(nums, lo + 1, end, k);
        }
        // 第k大的数在lo位置的左边
        else {
            // k-(end-lo+1)
            // (end-lo+1):表示从lo位置开始到end位置的元素个数,就是舍掉右半部分
            // 原来的第k大变成k-(end-lo+1)大
            return findKthLargest(nums, start, lo - 1, k - (end - lo + 1));
        }
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

这里写图片描述

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/48046265

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值