- 解法一,排序然后返回第k大
重點是降序的表示方法: greater<int> ()
class Solution {
public:
/*
* @param n: An integer
* @param nums: An array
* @return: the Kth largest element
*/
bool cmp(int a, int b){
return a > b;
}
int kthLargestElement(int n, vector<int> &nums){
// write your code here
sort(nums.begin(), nums.end(), greater<int> ());
return nums[n-1];
}
};
或者:
- heapsort
這個解法在lintcode上一直報錯狡恬,leetcodeAC - Kth Largest Element in an Array
class Solution {
public:
void heapify(vector<int> &nums, int heapsize, int index){
int largest = index;
int left = 2 * largest + 1;
int right = 2 * largest + 2;
if(nums[left] > nums[largest] && left < heapsize){
largest = left;
}
if(nums[right] > nums[largest] && right < heapsize){
largest = right;
}
if(largest != index){
swap(nums[index], nums[largest]);
heapify(nums, heapsize, largest);
}
}
int findKthLargest(vector<int>& nums, int k) {
int hp_size = nums.size();
for(int i = hp_size/2 - 1; i >= 0; i--){
heapify(nums, hp_size, i);
}
for(int i = 0; i < k; i++){
swap(nums[0], nums[hp_size - 1]);
hp_size--;
heapify(nums, hp_size, 0);
}
return nums[hp_size];
}
};
- quickselect
class Solution {
public:
/*
* @param n: An integer
* @param nums: An array
* @return: the Kth largest element
*/
int partition(vector<int> &nums, int left, int right){
int pivot = nums[left];
int l = left + 1;
int r = right;
while(l <= r){
if(nums[l] < pivot && nums[r] > pivot){
swap(nums[l++],nums[r--]);
}
if(nums[l] >= pivot ){
l++;
}
if(nums[r] <= pivot ){
r--;
}
}
swap(nums[left], nums[r]);
return r;
}
int kthLargestElement(int n, vector<int> &nums) {
// write your code here
int left = 0;
int right = nums.size() - 1;
while(1){
int index = partition(nums,left,right);
if(index == n-1){
return nums[n-1];
}
if(index > n - 1){
right = index - 1;
}
else{
left = index + 1;
}
}
}
};
- priority_queue
class Solution {
public:
/*
* @param n: An integer
* @param nums: An array
* @return: the Kth largest element
*/
int kthLargestElement(int n, vector<int> &nums) {
// write your code here
priority_queue<int> pq(nums.begin(),nums.end());
for(int i = 0 ; i < n - 1; i++){
pq.pop();
}
return pq.top();
}
};