[LeetCode] Kth Largest Element in an Array 数组中第k大的数字

时间:2015-05-30 07:02:46   收藏:0   阅读:297

 

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

 

原文:http://www.cnblogs.com/grandyang/p/4539757.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!