divide and conquer
题目:
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.
解法:
分而治之:
利用快速排序,pivot是子数组的第一个元素。大于关键点pivot的值放在左边,小于关键点pivot的值放在右边。如果关键点恰好是nums[k-1],那么该关键点就是数组的第k大的数。如果关键点
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int left = 0;
int right = nums.size()-1;
while (true) {
int pos = getPosition(nums, left, right);
if (pos == k-1) return nums[k-1];
if (pos > k-1) right = pos-1;
else left = pos+1;
}
}
int getPosition(vector<int> &nums, int left, int right) {
int pivot = nums[left];
int l = left+1, r = right;
while (l <= r) {
if (nums[l] < pivot && nums[r] > pivot) {
swap(nums[l], nums[r]);
}
if (nums[l] >= pivot) l++;
if (nums[r] <= pivot) r--;
}
swap(pivot, nums[r]);
return r;
}
};
优先队列:
优先队列可以从大到小自动排列,所以将前k-1个数据弹出,队头就是第k大数据。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
return nums[nums.size() - k];
}
};