LeetCode 之 Kth Largest Element in an Array — C++ 实现

来源:互联网 发布:淘宝上买东西怎样付款 编辑:程序博客网 时间:2024/05/02 02:45

Kth Largest Element in an Array

 

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.

在无序数组中找出第 k 大的元素。说明:第 k 大的元素是有序数组中从大到小将重复元素计算在内的第 k 个元素,而不是各不相同的第 k 个元素。 

例如,

给定数组 [3,2,1,5,6,4] 和 k = 2,返回 5。


分析:

    将数组元素从大到小排序,返回第 k-1 个元素即可。

class Solution {public:    int findKthLargest(vector<int>& nums, int k) {        sort(nums.begin(), nums.end(), cmp);                return nums[k-1];    }        static bool cmp(int first, int second)    {        return (first > second);    }};


0 0