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

[LeetCode] Kth Largest Element in an Array

时间:2015-05-23 12:50:52      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

Find the kth largest element in an unsorted array.

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.

https://leetcode.com/problems/kth-largest-element-in-an-array/

 

利用快排的思想,平均时间复杂度O(n),4ms AC。最坏情况下会退化成O(n^2),比如说数组是从小到大排好序的而要找的是最大值。
 1 class Solution {
 2 public:
 3     int findKthLargest(vector<int>& nums, int k) {
 4         int L = 0, R = nums.size() - 1;
 5         while (L < R) {
 6             int left = L, right = R;
 7             int key = nums[left];
 8             while (left < right) {
 9                 while (left < right && nums[right] < key) --right;
10                 nums[left] = nums[right];
11                 while (left < right && nums[left] >= key) ++left;
12                 nums[right] = nums[left];
13             }
14             nums[left] = key;
15             if (left == k - 1) return nums[k - 1];
16             else if (left > k - 1) R = left - 1;
17             else L = left + 1;
18         }
19         return nums[k - 1];
20     }
21 };

 

[LeetCode] Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4523941.html

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