leetcode 215 Kth Largest Element in an Array : 快排

在无序的数组中找到第k大的元素,也就是若长度为n的数组从小到大排列时,下标为n-k的元素。

注意Example2:第4大的元素是4,也就是数组中出现的两个5分别是第2大和第3大的数字。                   

解法一:直接将数组从大到小排序,取出下标为n-k的元素。

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        return nums[nums.size() - k];
    }
};

解法二:

猜你喜欢

转载自www.cnblogs.com/Bella2017/p/10134111.html