lc 215 Kth Largest Element in an Array
215 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.
multiset Accepted
投机取巧的方法,利用stl中multiset的特性,自动实现从小到大的排序,并且允许有相同元素的存在,但是要注意,multiset不能用下标获取元素,所以需删除之前不必要的元素,用*ans.begin()的方法获取首元素。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
multiset<int> ans;
for (auto i : nums) {
ans.insert(i);
}
while (ans.size() > k) ans.erase(ans.begin());
return *ans.begin();
}
};
分治 Accepted
类似于快排的原理,其中也蕴含了分治的思想。
class Solution {
public:
void swap(vector<int>& nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
int p = quick(nums, 0, n-1, n-k+1);
return nums[p];
}
int quick(vector<int>& a, int low, int high, int k) {
int i = low, j = high, pivot = a[high];
while (i < j) {
if (a[i++] > pivot) swap(a, --i, --j);
}
swap(a, i, high);
int m = i - low + 1;
if (m == k) return i;
else if (m > k) return quick(a, low, i - 1, k);
else return quick(a, i + 1, high, k - m);
}
};
将递归转化成递推
思想和上面的方法是一样的,但是将递归转化成递推。
void swap(vector<int>& nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
int findKthLargest(vector<int>& nums, int k) {
k = nums.size() - k;
int l = 0, r = nums.size() - 1;
while (l <= r) {
int i = l;
for (int j = l + 1; j <= r; j++)
if (nums[j] < nums[l]) swap(nums, j, ++i);
swap(nums, l, i);
if (k < i) r = i - 1;
else if (k > i) l = i + 1;
else return nums[i];
}
return -1;
}