LeetCode Kth Largest Element in an Array
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.
都第几次多这样的题了,还是bug多得飞起
class Solution { public: int findKthLargest(vector<int>& nums, int k) { int len = nums.size(); int start = 0; int end = len; // convert to kth smallest element sematic k = len - k + 1; while (start < end) { int idx = partition(nums, start, end); if (idx == k - 1) { return nums[idx]; } else if (idx < k - 1) { start = idx + 1; k = k - (idx - start + 1); } else { end = idx; } } return nums[start]; } int partition(vector<int>& nums, int start, int end) { if (start >= end) { return -1; } int pv = nums[--end]; int div = start; for (int i=start; i<end; i++) { if (nums[i] < pv) { swap(nums[i], nums[div]); div++; } } swap(nums[div], nums[end]); return div; } };
重做了一遍,感觉上面第一个函数似乎有点问题,但是为什么也能过呢?
class Solution { public: int findKthLargest(vector<int>& nums, int k) { int len = nums.size(); k = len - k; int pi = 0; int start = 0, end = len; while ((pi = partition(nums, start, end)) != k) { if (pi > k) { end = pi; } else if (pi < k) { start = pi + 1; } else { break; } } return nums[pi]; } int partition(vector<int>& nums, int start, int end) { if (start >= end) { return -1; } int pv = nums[--end]; int di = start; for (int i=start; i<end; i++) { if (nums[i] < pv) { swap(nums[i], nums[di++]); } } swap(nums[end], nums[di]); return di; } };
又一次,还是有bug,简化一点
class Solution { public: int findKthLargest(vector<int>& nums, int k) { int len = nums.size(); int rk = len - k; dfs(nums, 0, len, rk); return nums[rk]; } void dfs(vector<int>& nums, int start, int end, int k) { if (start >= end) { return; } int div = partition(nums, start, end); if (div < k) { dfs(nums, div + 1, end, k); } else if (div > k) { dfs(nums, start, div, k); } } int partition(vector<int>& nums, int start, int end) { if (start >= end) { return start; } int pv = nums[--end]; int div= start; for (int i=start; i<end; i++) { if (nums[i] < pv) { swap(nums[div++], nums[i]); } } swap(nums[div], nums[end]); return div; } };