Kth Largest Element in an Array
2015-05-23 14:05
323 查看
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
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
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.
class Solution { public: int visit(vector<int> &nums, int k, int left, int right) { int pivot = nums[right]; int p = left-1; int q = left; while (q < right) { if (nums[q] < pivot) { p++; swap(nums[p], nums[q]); } q++; } swap(nums[p+1], nums[right]); if (p+1 == k) { return p+1; } else if (p+1 > k) { return visit(nums, k, left, p); } else { return visit(nums, k, p+2, right); } } int findKthLargest(vector<int>& nums, int k) { int n = nums.size(); k = n - k; int index = visit(nums, k, 0, n-1); return nums[index]; } };
相关文章推荐
- LeetCode#215 Kth Largest Element in an Array
- Kth Largest Element in an Array 解答
- LeetCode@Array_215_Kth_Largest_Element_in_an_Array
- 堆排序 && Kth Largest Element in an Array
- Leetcode 215 Kth Largest Element in an Array(快速选择)
- LeetCode – Kth Largest Element in an Array (Java)
- [LeetCode] Kth Largest Element in an Array (找出数组的第k大的元素)
- 215. Kth Largest Element in an Array
- [LeetCode 215]Kth Largest Element in an Array (分治法/快速排序)
- Kth Largest Element in an Array
- LeetCode Devide & Conquer problem || Kth Largest Element in an Array
- Kth Largest Element in an Array
- 题解:Kth Largest Element in an Array
- LeetCode:Kth Largest Element in an Array
- 215. Kth Largest Element in an Array
- Kth Largest Element in an Array
- 算法设计课作业系列2——Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- [Leetcode 215, Medium] Kth Largest Element in an Array