LeetCode-Kth Largest Element in an Array-解题报告

来源:互联网 发布:淘宝网装饰腰带 编辑:程序博客网 时间:2024/06/05 04:34

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

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.


类似快速排序,选取第一个元素作为分界元素,快速排序后

s...i...e

如果i - s + 1 == k return nums[i]

如果i-s + 1 > k return find_k_largest(nums, k, s, i - 1);

其他情况 return  find_k_largest(nums, k - (i - s + 1), i + 1, e);

当然了你也可以随机选取一个元素作为参考元素

<span style="font-size:14px;">class Solution {public:   int findKthLargest(vector<int>& nums, int k) {return find_k_largest(nums, k, 0, nums.size() - 1);}int find_k_largest(vector<int>& nums, int k, int s, int e){int i = s, j = e, tmp = nums[i];while (i < j){while (i < j && nums[j] <= tmp)--j;nums[i] = nums[j];while (i < j && nums[i] > tmp)++i;nums[j] = nums[i];}nums[i] = tmp;if (i - s + 1 == k)return nums[i];else if(i - s + 1 > k)return find_k_largest(nums, k, s, i - 1);else return find_k_largest(nums, k - (i - s + 1), i + 1, e);}};</span>


0 0