栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode-215. Kth Largest Element in an Array [C++][Java]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode-215. Kth Largest Element in an Array [C++][Java]

LeetCode-215. Kth Largest Element in an Arrayhttps://leetcode.com/problems/kth-largest-element-in-an-array/

题目描述

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Constraints:

1 <= k <= nums.length <= 104-104 <= nums[i] <= 104

解题思路

【C++】

快排partition

1. 循环
class Solution {
public:
    int findKthLargest(vector& nums, int k) {
        if (k <= 0 || k > nums.size()) {return -1;}
        k--;
        int l = 0, h = nums.size() - 1, idx = partition(nums, l, h);
        while(idx != k ) { 
            if(idx < k) {
                idx = partition(nums, idx+1, h);
            } else {
                idx = partition(nums, l, idx-1);
            }
        }
        return nums[k];
    }

    int partition(vector& nums, int l, int h) {
        int pivot = nums[l];
        while(l < h) {
            while(pivot>=nums[h] && l 
2. 递归 
class Solution {
public:
    int findKthLargest(vector& nums, int k) {
        if (k <= 0 || k > nums.size()) {return -1;}
        partition(nums, 0, nums.size() - 1, --k);
        return nums[k];
    }

    void partition(vector& nums, int l, int h, int k) {
        int pivot = nums[l], low = l, high = h;
        while(l < h) {
            while(pivot>=nums[h] && l k) {partition(nums, low, l - 1, k);}
        else {partition(nums, l + 1, high, k);}
    }
};
【Java】
class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums.length == 0 || nums.length < k) { return -1;}
        partition(nums, 0, nums.length - 1, --k);
        return nums[k];
    }

    void partition(int[] nums, int low, int high, int k) {
        int pivot = nums[low], l = low, h = high;
        while(l < h) {
            while(pivot >= nums[h] && l < h) h--;
            nums[l] = nums[h];
            while(pivot <= nums[l] && l < h) l++;
            nums[h] = nums[l];
        }
        nums[l] = pivot;
        if (l == k) {return;}
        else if (l > k) {partition(nums, low, l - 1, k);}
        else {partition(nums, l + 1, high, k);}
    }
}

参考文献

【1】使用快速排序方法求第K大的数_qq_42211773的博客-CSDN博客_求第k大的数

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/736967.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号