lc 数组中的第K个最大元素
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
代码:
class Solution { public: int findKthLargest(vector<int>& nums, int k) { k--; return solve(nums, 0, nums.size()-1, k); } int solve(vector<int>& nums, int low, int high, int k) { int privot = nums[low]; int ll = low; int hh = high; int index = partition(nums, low, high); if(index == k) return nums[k]; else if(k < index) { return solve(nums, ll, index-1, k); } else { return solve(nums, index+1, hh, k); } } int partition(vector<int>& nums, int low, int high) { if(low == high) return low; int privot = nums[low]; while(low < high) { while(low < high && nums[high] <= privot) high--; nums[low] = nums[high]; while(low < high && nums[low] >= privot) low++; nums[high] = nums[low]; // cout << "======" << endl; } nums[low] = privot; return low; } };
思路:参考快排partition 思想,再递归,一直到 partition 返回的坐标是 k,复杂度是O(n),因为费时操作是 partition。
posted on 2020-05-18 00:42 FriskyPuppy 阅读(201) 评论(0) 编辑 收藏 举报