2.7 Kth Largest Element in an Array
Description
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example, Given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
Link :
Method
use quicksort method to select the kth elements
Time and Space Complexity
o(n)
Code
using the most left element as a pivot public class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length == 0 || k == 0){ return 0; } return partition(nums, 0, nums.length - 1, k);
}
public int partition(int[] nums, int left, int right, int k){
//int pivot = left + (int)( Math.random() * (right - left + 1)); if (left == right) { return nums[left]; } int l = left; int r = right; int p = nums[left]; while (l < r){ while (l < r && nums[r] <= p){ r--; } nums[l] = nums[r]; while (l < r && nums[l] >= p){ l++; } nums[r] = nums[l]; } nums[l] = p; //System.out.println("l" + l); if (l == k - 1){ return nums[l]; } else if (l < k - 1){ return partition(nums, l + 1, right, k); } else { return partition(nums, left, l - 1, k); }
} }