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大的数字。先看一种利用c++的STL中的集成的排序方法,不用我们自己实现,这样的话这道题只要两行就完事了,代码如下:
解法一
class Solution { public: int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); return nums[nums.size() - k]; } };
参考资料:
https://leetcode.com/discuss/37724/solutions-nlogn-sort-klogn-heapsort-average-quicksort-kind
http://blog.csdn.net/kangrydotnet/article/details/45973575
时间: 2024-10-11 22:45:52