【28】215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

  • Total Accepted: 108089
  • Total Submissions: 286063
  • Difficulty: Medium
  • Contributors: Admin

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.

Solution: 1 sort 2 partition - time limitation

 1 class Solution {
 2 public:
 3 //最简单暴力的方法就是先对整个数组排序,然后返回 nums[k-1] 即可。时间复杂度O(nlogn)。
 4 //采用快速排序的思路,但是不对整个数列排序。
 5 //partition(int[] a, int lo, int hi)方法和快速排序一样,选取该分段中的第一个数为标兵(pivot)。所有大于pivot的数放到其左侧,小于pivot的数放到其右侧。最后返回pivot的位置。在经过一次partition方法之后,根据k和pivot的位置,来选择是对左侧部分还是对右侧部分继续进行partition。该方法时间复杂度为O(n)。
 6     int findKthLargest(vector<int>& nums, int k) {
 7         //sort(nums.begin(), nums.end());
 8         //return nums[nums.size() - k];
 9         k--;
10         int l = 0, r = nums.size() - 1;
11         int idx = 0;
12         while(l < r){
13             idx = partition(nums, l, r);
14             if(k < idx) r = idx - 1;
15             else if(k > idx) l = idx + 1;
16             else return nums[idx];
17         }
18         
19         return nums[l];
20     }
21     
22     int partition(vector<int>& nums, int left, int right){
23         int l = left;
24         int r = right;
25         int pivot = nums[l];
26         while(l < r){
27             while(l < r && nums[r] < pivot) r--;
28             nums[l] = nums[r];
29             while(l < r && nums[l] > pivot) l++;
30             nums[r] = nums[l];
31         }
32         nums[l] = pivot;
33         return l;
34     }
35 };

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2017-02-08 07:48  会咬人的兔子  阅读(121)  评论(0编辑  收藏  举报