码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-30 07:05:25      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

 

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

 

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!