Skip to content

Latest commit

 

History

History
87 lines (66 loc) · 1.58 KB

20221208.md

File metadata and controls

87 lines (66 loc) · 1.58 KB

Algorithm

215. Kth Largest Element in an Array

Description

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.

You must solve it in O(n) time complexity.

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 {
    public int findKthLargest(int[] nums, int k) {
        int n = nums.length, low = 0, high = n-1;
        while(low<=high){
           int x = partition(nums, low, high);
           if(n-k==x){
               return nums[x];
           }else if(x<n-k){
               low = x+1;
           }else{
               high = high-1;
           }
        }
        return low;
    }

    private int partition(int[] nums, int low, int high){
        int i = low;
        int j = high;
        int povit = nums[i];
        while(i<j){
            while(i<j&&povit<nums[j]){
                j--;
            }
            if(i<j){
                nums[i] = nums[j];
                nums[j] = povit;
                i++;
            }
            while(i<j&&nums[i]<povit){
                i++;
            }
            if(i<j){
                nums[j] = nums[i];
                nums[i] = povit;
                j--;
            }
        }
        return i;
    }
}

Discuss

Review

Tip

Share