分治稍微講了講簡單的第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的練習,還有機會