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

LeetCode-215. Kth Largest Element in an Arrayicon-default.png?t=M0H8https://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大的数

你可能感兴趣的:(LeetCode刷题怪,leetcode,java,c++)