2023-08-14 Daily Challenge

Today I have done leetcode's August LeetCoding Challenge with cpp.

August LeetCoding Challenge 14

Description

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.

Can you solve it without sorting?

 

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 <= 105
  • -104 <= nums[i] <= 104

Solution

class Solution {
  int KthLargest(vector<int>& nums, int begin, int len, int k) {
    if(len <= 1) return nums[begin];
    const int pivot = nums[begin + rand()%len];
    int front = begin, index = begin, back = begin+len;
    while(index < back) {
      if(nums[index] < pivot) {
        swap(nums[index], nums[front]);
        index += 1;
        front += 1;
      } else if(nums[index] > pivot) {
        back -= 1;
        swap(nums[index], nums[back]);
      } else {
        index += 1;
      }
    }
    cout << endl;
    if(front >= k) return KthLargest(nums, begin, front-begin, k);
    else if (back < k) return KthLargest(nums, back, begin+len-back, k);
    return pivot;
  }
public:
  int findKthLargest(vector<int>& nums, int k) {
    int len = nums.size();
    return KthLargest(nums, 0, len, len-k+1);
  }
};

// Accepted
// 40/40 cases passed (72 ms)
// Your runtime beats 96.84 % of cpp submissions
// Your memory usage beats 74.16 % of cpp submissions (45.5 MB)