【2019/03/03】
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.
【思路一】
- 对无序数组排序;
- 返回第K个数;
- 时间复杂度是O(nlogn),空间复杂度是O(1)
【代码一】
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
return nums[nums.size() -k];
}
};
【思路二】(我其实有点没弄懂,主要是不知道快排吧~~~)
- 对数组从大到小进行快排;
- 分割数组,如果pivot在第k-1位,返回piovt;
- [数组分割]如果piovt在k-1的右边,说明要求的数字在左半部分,更新右边界
- 否则更新左边界
- 重复[数组分割]
【代码二】
class Solution{
public:
int findKthLargest(vector<int>& nums, int k){
int left = 0, int right = nums.size() - 1;
while(ture){
int pos = partition(nums, left, right);
if (pos == k - 1) return mums[pos];
else if ( pos > k -1) right = pos -1;
else left = pos + 1;
}
}
int partition(vector<int>& nums, int left, int right){ //分割数组的函数
int piovt = nums[left], l = left + 1; r = right; //piovt从最左边开始取,left和right都是索引,l从第二个开始取值
while( l < r){ //
if(nums[l] < piovt && nums[r] > piovt){
swap(nums[l++], nums[r--]);
}
if(nums[l] >= piovt) ++l;
if(nums[r] <= piovt) --r;
}
swap(nums[left], nums[r]);
return r;
}
};