码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 数组中的第K个最大元素

时间:2021-05-03 11:51:04      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:rgba   return   https   示例   ndk   strong   for   图片   inf   

在未排序的数组中找到第 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
说明:

你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

采用最大堆排序,只是需要要弹出k次即可。

    public int findKthLargest(int[] nums, int k) {
        int length = nums.length;
        for (int i = length / 2 - 1; i >= 0 ; i--) {
            find(nums, i, length);
        }
        for(int i = 0; i < k - 1; i++) {
            nums[0] = nums[length - 1 - i];
            find(nums, 0, length - 1 - i);
        }
        return nums[0];
    }

    private static void find (int[] nums, int st, int end) {
        int index = 2 * st + 1;
        if (index >= end) {
            return;
        }
        index = index + 1 >= end ? index : nums[index] > nums[index + 1] ? index : index + 1;
        if (nums[index] > nums[st]) {
            int c = nums[index];
            nums[index] = nums[st];
            nums[st] = c;
            find(nums, index, end);
        }
    }

技术图片

leetcode 数组中的第K个最大元素

标签:rgba   return   https   示例   ndk   strong   for   图片   inf   

原文地址:https://www.cnblogs.com/wangzaiguli/p/14721937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!