[LeetCode]Kth Largest Element in an Array

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.

https://leetcode.com/problems/kth-largest-element-in-an-array/

 

 


 

 

排一下序直接输出就好了。

我还以为要剔掉重复的数字,然后被这个test case教做人orz。

Input: [-1,-1], 2
Output: NaN
Expected: -1

不过这题是medium难度哎,排个序是不是算作弊...

 1 /**
 2  * @param {number[]} nums
 3  * @param {number} k
 4  * @return {number}
 5  */
 6 var findKthLargest = function(nums, k) {
 7     nums.sort(function(a, b){
 8         if(a > b){
 9             return -1;
10         }else if(a < b){
11             return 1;
12         }else{
13             return 0;
14         }
15     });
16     return nums[k - 1];
17 };

 

posted @ 2015-05-23 17:47  `Liok  阅读(241)  评论(0编辑  收藏  举报