C++求出给定数组中第k大的元素

可以利用快速选择算法来解决。快速选择算法是基于快速排序算法的一种变种,它可以在O(n)的时间复杂度内找到第k大的元素。

快速选择算法的基本思路是选择一个pivot元素,将数组分成小于pivot和大于pivot两部分。如果小于pivot的元素个数大于等于k,则在小于pivot的部分继续递归寻找第k大的元素;否则在大于pivot的部分递归寻找第k大的元素。当小于pivot的元素个数等于k时,pivot即为第k大的元素。

#include <iostream>
#include <vector>
using namespace std;

int partition(vector<int>& nums, int left, int right) {
    int pivot = nums[left];
    int i = left, j = right;
    while (i < j) {
        while (i < j && nums[j] <= pivot) j--;
        nums[i] = nums[j];
        while (i < j && nums[i] >= pivot) i++;
        nums[j] = nums[i];
    }
    nums[i] = pivot;
    return i;
}

int quickSelect(vector<int>& nums, int left, int right, int k) {
    int pivotIndex = partition(nums, left, right);
    int numLeft = pivotIndex - left + 1;
    if (numLeft == k) return nums[pivotIndex];
    else if (numLeft > k) return quickSelect(nums, left, pivotIndex-1, k);
    else return quickSelect(nums, pivotIndex+1, right, k-numLeft);
}

int findKthLargest(vector<int>& nums, int k) {
    int n = nums.size();
    if (n < k) return -1;
    return quickSelect(nums, 0, n-1, k);
}

int main() {
    vector<int> nums = {3, 2, 1, 5, 6, 4};
    int k = 2;
    int ans = findKthLargest(nums, k);
    cout << "The " << k << "th largest element is " << ans << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/SYC20110120/article/details/134623700