1、堆
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
priority_queue<int,vector<int>,greater<int>> q;
for (int i = 0; i < k; i++) {
q.push(nums[i]);
}
for (int i = k; i < n; i++) {
int temp = q.top();
if (nums[i] > temp) {
q.pop();
q.push(nums[i]);
}
}
return q.top();
}
2、类似快排
void helper(vector<int>& v, int left, int right, int& k) {
if (right <= left)
return;
int pivot = v[left];
int i = left, j = right;
while (i < j) {
while (i < j && v[j] < pivot) {
j--;
}
if (i < j)
v[i++] = v[j];
while (i < j && v[i] > pivot) {
i++;
}
if (i < j)
v[j--] = v[i];
}
v[i] = pivot;
if (k > i + 1) {
helper(v, i + 1, right, k);
}
if (k < i) {
helper(v, left, i - 1, k);
}
return;
}
static bool cmp(int a, int b) {
return a > b;
}
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
helper(nums, 0, n - 1, k);
sort(nums.begin(), nums.begin() + k ,cmp);
return nums[k-1];
}
3、sort
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end() ,greater<int>());
return nums[k-1];
}
不要盲目追求击败率。。。