标签:
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; } };
LeetCode Kth Largest Element in an Array
标签:
原文地址:http://www.cnblogs.com/lailailai/p/4526872.html