LeetCode 215. Kth Largest Element in an Array

Description

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.

Solution

将数组排序,然后直接通过索引返回第k大的数字

int findKthLargest(vector<int>& nums, int k){
    sort(nums.begin(), nums.end());
    reverse(nums.begin(), nums.end());
    return nums[k-1];
}

利用分治思想写出快速选择算法耶鲁大学:QuickSelect算法

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

int findKthLargest(vector<int>& nums, int k){
    vector<int> left;
    vector<int> right;
    int pivot = nums[0];
    for(int i = 1; i < nums.size(); i++){
        if(nums[i] <= pivot) left.push_back(nums[i]);
        else right.push_back((nums[i]));
    }
    if(k <= right.size()) return findKthLargest(right, k);
    else if(k-1 == right.size()) return pivot;
    else return findKthLargest(left, k-right.size()-1);
}

int main(){
    int ary[10] = {3, 2, 1, 5, 6, 4};
    vector<int> vec(ary, ary+6);
    cout<<findKthLargest(vec, 2);
}

快速选择算法在LeetCode平台上会出现内存超限(Memory Limit Exceeded)的问题,这与C++中内存的管理模式有关:vector内存空间只会增长,不会减小。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值