C#版 - Leetcode 215. Kth Largest Element in an Array-题解
在线提交: https://leetcode.com/problems/kth-largest-element-in-an-array/
Description
Find the k th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
Difficulty:
Medium
Total Accepted: 219.3K
Total Submissions: 531.5K
Contributor: mithmatt
Related Topics Divide and ConquerHeap
Similar Questions Wiggle Sort IITop K Frequent ElementsThird Maximum Number
思路:
使用List,定义其Sort函数接口,取出第k大的值(List的第k-1个元素)即可。
已AC代码:
public class Solution
{
public int FindKthLargest(int[] nums, int k)
{
int kthMax = 0;
var list = new List<int>();
foreach (var num in nums)
list.Add(num);
list.Sort((x, y) => -x.CompareTo(y));
if (list.Count >= k)
kthMax = list.ElementAtOrDefault(k-1);
return kthMax;
}
}
Rank:
You are here!
Your runtime beats 94.55 %
of csharp submissions.