分治稍微讲了讲简单的第k大的数
就简单的在leetcode上面练练手
题目:
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.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
完整代码和思考过程如下
class Solution {
public:
int divide(vector<int> &nums, int left, int right, int k) {
int mid = left + (right -left) / 2;//选取一个轴心
int l = left;
int r = right;
int t = nums[mid];//标记轴心的值
//l在r的右边的时候跳出循环。l, r中间有可能会隔着一个数。
while (l <= r) {
while (nums[l] > t) l++;//l向右寻找第一个不大于t的数
while (nums[r] < t) r--;//r向左寻找第一个不小于t的数
//如果l在r的左边,或者l与r重合,则将找到的两个数交换,沿途经过的数都已经满足条件
if (l <= r) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
l++;
r--;
}
}
//r没有越界,k在r的左边
if (left < r && r >= k) return divide(nums, left, r, k);
//l没有越界,k在l的右边
if (right > l && l <= k) return divide(nums, l, right, k);
//分两种情况,如果出现r, k, l这种情况,则说明第k大的数就在k这个位置
//然后就是上述函数递归到最后,k出现在区间边缘,r,l重合在k(说明已经有序)l或者r越界,即找到了k。
return nums[k];
}
int findKthLargest(vector<int>& nums, int k) {
return divide(nums, 0, nums.size()-1, k-1);
}
};
其实感觉跟书上思想有些不一样?
改天再按照之前讲的思路再写一遍好了。
其实这东西让我闭着眼睛写还是写不出来,要仔细想半天细节。
总感觉还能更进一步。
而且leetcode上还有类似的Kth Largest的练习,还有机会