题解 | #寻找第K大#
寻找第K大
https://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
using System;
using System.Collections.Generic;
class Solution {
SortedDictionary<int, int> sortDic = new SortedDictionary<int, int>();
public int findKth(List<int> a, int n, int K) {
// write code here
if (n == 0 || K > a.Count) return int.MaxValue;//找不到
List<int> res = new List<int>();
for (int i = 0; i < a.Count; i++) {
if (sortDic.ContainsKey(a[i])) {
sortDic[a[i]] += 1;
} else {
sortDic.Add(a[i], 1);
}
}
foreach (KeyValuePair<int, int> item in sortDic) {
int temp = item.Value;
while (temp-- != 0) {
res.Add(item.Key);
}
}
return res[res.Count - K];
}
}
查看15道真题和解析