Find the kth largest element in an unsorted array.
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.
https://leetcode.com/problems/kth-largest-element-in-an-array/
利用快排的思想,平均时间复杂度O(n),4ms AC。最坏情况下会退化成O(n^2),比如说数组是从小到大排好序的而要找的是最大值。非递归,空间复杂度O(1)。
1 class Solution { 2 public: 3 int findKthLargest(vector<int>& nums, int k) { 4 int L = 0, R = nums.size() - 1; 5 while (L < R) { 6 int left = L, right = R; 7 int key = nums[left]; 8 while (left < right) { 9 while (left < right && nums[right] < key) --right; 10 nums[left] = nums[right]; 11 while (left < right && nums[left] >= key) ++left; 12 nums[right] = nums[left]; 13 } 14 nums[left] = key; 15 if (left == k - 1) return nums[k - 1]; 16 else if (left > k - 1) R = left - 1; 17 else L = left + 1; 18 } 19 return nums[k - 1]; 20 } 21 };