一级标题
算法
public class Solution {
public IList<string> TopKFrequent(string[] words, int k) {
Dictionary<string, int> cnt = new Dictionary<string, int>();
foreach (string word in words)
{
if (cnt.ContainsKey(word))
{
cnt[word]++;
}
else
{
cnt.Add(word, 1);
}
}
List<string> rec = new List<string>();
foreach (var item in cnt)
{
rec.Add(item.Key);
}
rec.Sort(
delegate (string word1, string word2) {
return cnt[word1] == cnt[word2] ? word1.CompareTo(word2) : cnt[word2] - cnt[word1];
}
);
return rec.GetRange(0, k);
}
}
重点
1.list.Sort() 排序,里面跟着是一个委托
2.list.GetRange(index,k) 从index开始获得k个数据