DEV Community

Wenqi Jiang
Wenqi Jiang

Posted on

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.

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Enter fullscreen mode Exit fullscreen mode

Constraints:

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

Solutions

Solution 1

Intuition

templates

void quick_sort(int q[], int l, int r)
{
    if (l >= r) return;

    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while (i < j)
    {
        do i ++ ; while (q[i] < x);
        do j -- ; while (q[j] > x);
        if (i < j) swap(q[i], q[j]);
    }
    quick_sort(q, l, j), quick_sort(q, j + 1, r);
}
Enter fullscreen mode Exit fullscreen mode
private void quickSort(int[] nums, int l, int r) {
    if (l >= r) {
        return;
    }
    int i = l - 1, j = r + 1, x = nums[l + r >> 1];
    while (i < j) {
        do {
            i++;
        } while (nums[i] < x);
        do {
            j--;
        } while (nums[j] > x);
        if (i < j) {
            swap(nums, i, j);
        }
    }
    quickSort(nums, l, j);
    quickSort(nums, j + 1, r);

}

private void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}
Enter fullscreen mode Exit fullscreen mode

Code

class Solution {
    private int quickSort(int[] nums, int l, int r, int k) {
        if (l >= r) {
            return nums[l];
        }

        int i = l - 1, j = r + 1, x = nums[l + r >> 1];
        while (i < j) {
            do {
                i++;
            } while (nums[i] < x);
            do {
                j--;
            } while (nums[j] > x);
            if (i < j) {
                swap(nums, i, j);
            }
        }
        int s1 = j - l + 1 ;
        if (k <= s1) {
            return quickSort(nums, l, j, k);
        } else {
            return quickSort(nums, j + 1, r, k - s1);
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }


    public int findKthLargest(int[] nums, int k) {
        return quickSort(nums, 0, nums.length-1, nums.length - k + 1);
    }
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(nlogn)
  • Space: O(logn)

Solution 2

Intuition

Code


Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time:
  • Space:

Top comments (0)