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.
解决这种问题方法的核心还是排序,就比谁家排序方法更快了2333。。
三种方法:快排、priority_queue、标准库里的sort方法。
如果没有shuffle函数,运行时间是26ms,添加了以后是13ms。这个用咱大二的《数据结构与程序设计》中的快排方法理解起来嗖嗖快,解这题没必要完全排序,利用核心思想找出第K大的数就可以了。
快排
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
//STL中的函数random_shuffle()用来对一个元素序列进行重新排序(随机的)
random_shuffle(nums.begin(), nums.end());
int low = 0, high = nums.size() - 1;
while (1) {
/*
无需加以low < high的判断
具体情况具体分析,以下代码中只要pivot == k - 1 就会返回数值
一种最后的情况:只剩下一个数,执行一次partition后,pivot就是该数,之后即返回
而不是像《数据结构》p353的示例代码,若没有low<high的判断
会不断调用最终的partition,即使partition中的循环不执行
*/
int pivot = partition(nums, low, high);
if (pivot == k - 1) return nums[pivot];
else if (pivot > k - 1) {
high = pivot - 1;
}
else { // pivot < k - 1
low = pivot + 1;
}
}
}
int partition(vector<int>& nums, int low, int high) {
int pivot, last_small;
pivot = nums[low];
last_small = low;
for (int i = low + 1; i <= high; i++) {
if (nums[i] > pivot) {
last_small++;
swap(nums[i], nums[last_small]);
}
}
swap(nums[last_small], nums[low]);
return last_small;
}
};
priority_queue
/*利用priority_queue的特性*/
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> pq(nums.begin(), nums.end());
for (int i = 1; i < k; i++) {
pq.pop();
}
return pq.top();
}
};
标准库大法好——sort()函数
/利用C++标准库的排序函数/
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
sort(nums.begin(), nums.end());
return nums[n - k];
}
};
discussion中还有堆排序的,虽然去年学过,突然不想做了2333
怎么感觉我的博客画风有点歪了蛤蛤蛤蛤蛤蛤