数组中第K个最大元素
生活随笔
收集整理的這篇文章主要介紹了
数组中第K个最大元素
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在未排序的數組中找到第 k 個最大的元素。請注意,你需要找的是數組排序后的第 k 個最大的元素,而不是第 k 個不同的元素。
- 示例 1:
- 示例 2:
說明:
你可以假設 k 總是有效的,且 1 ≤ k ≤ 數組的長度。
快排參考
#include <iostream> #include <vector> using namespace std;void quickSort(vector<int>& nums, int begin, int end); void swap(int& first, int& second); int getIndex(vector<int>& nums, int start, int end); int main() {vector<int> nums = {1,23,67,24,87,45,25,7,68,58,45,34};quickSort(nums, 0, nums.size() - 1);for (const auto& x: nums) {cout << x << " ";}cout << endl;return 0; }void quickSort(vector<int>& nums, int start, int end) {if (start < end) {int index = getIndex(nums, start, end);quickSort(nums, start, index-1);quickSort(nums, index+1, end);} }int getIndex(vector<int>& nums, int start, int end) {int tmp = nums[start];int low = start;int high = end;while(low < high) {while(low < high && nums[high] >= tmp) {high--;}nums[low] = nums[high];while(low < high && nums[low] <= tmp) {low++;}nums[high] = nums[low];}nums[low] = tmp;return low; }void swap(int& first, int& second) {int tmp = first;first = second;second = tmp; }- 基于快排解決第K個最大元素
- 優化,使用隨機的index
總結
以上是生活随笔為你收集整理的数组中第K个最大元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 构建最小堆、最大堆
- 下一篇: 漯河治疗无精症最好的医院推荐