LintCode-5.第k大元素

第k大元素

在数组中找到第k大的元素

注意事项

你可以交换数组中的元素的位置

样例

  • 给出数组 [9,3,2,4,8],第三大的元素是 4
  • 给出数组 [1,2,3,4,5],第一大的元素是 5,第二大的元素是 4,第三大的元素是 3,以此类推

挑战

要求时间复杂度为O(n),空间复杂度为O(1)

标签

快速排序 排序

code

class Solution {
public:
/*
* param k : description of k
* param nums : description of array and index 0 ~ n-1
* return: description of return
*/
int kthLargestElement(int k, vector nums) {
// write your code here
multiset set;

for(int i=0; i<nums.size(); i++) {
if(set.size() < k) {
set.insert(nums[i]);
}
else {
if(nums[i] >= set.begin()) {
set.erase(
set.begin());
set.insert(nums[i]);
}
}
}
return *set.begin();
}
};

posted @ 2017-05-04 16:39  LiBaoquan  阅读(697)  评论(0)    收藏  举报