标签:
https://leetcode.com/problems/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.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
排一下序直接输出就好了。
我还以为要剔掉重复的数字,然后被这个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 };
[LeetCode]Kth Largest Element in an Array
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4524630.html