码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] 第k大元素

时间:2015-06-28 18:44:50      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

基于快速排序:

 1 class Solution {
 2 public:
 3     /*
 4      * param k : description of k
 5      * param nums : description of array and index 0 ~ n-1
 6      * return: description of return
 7      */
 8     int kthLargestElement(int k, vector<int> nums) {
 9         // write your code here
10         int left = 0, right = nums.size() - 1;
11         while (true) {
12             int pos = partition(nums, left, right);
13             if (pos == k - 1) return nums[pos];
14             if (pos < k - 1) left = pos + 1;
15             if (pos > k - 1) right = pos - 1;
16         }
17     }
18 private:
19     int partition(vector<int>& nums, int left, int right) {
20         int pivot = nums[left];
21         int l = left + 1, r = right;
22         while (l <= r) {
23             if (nums[l] < pivot && nums[r] > pivot)
24                 swap(nums[l++], nums[r--]);
25             if (nums[l] >= pivot) l++;
26             if (nums[r] <= pivot) r--;
27         }
28         swap(nums[left], nums[r]);
29         return r;
30     }
31 };

 

[LintCode] 第k大元素

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4605828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!