饭后小甜点leetcode——桶排序的应用

文章目录

      • 桶排序的应用
          • 前K个高频元素
          • 根据字符出现频率排序
          • 前k个高频单词

桶排序的应用


前K个高频元素

leetcode题目地址

public IList<int> TopKFrequent(int[] nums, int k)
{
    var res = new List<int>();
    var dict = new Dictionary<int, int>();
    var bucket = new List<int>[nums.Length + 1];
    foreach (var num in nums)
    {
        if (!dict.ContainsKey(num))
            dict.Add(num, 0);
        dict[num]++;
    }
    foreach (var item in dict)
    {
        if (bucket[item.Value] == null)
            bucket[item.Value] = new List<int>();
        bucket[item.Value].Add(item.Key);
    }
    for (var i = bucket.Length - 1; i >= 0; i--)
    {
        if (bucket[i] == null) continue;
        foreach (var item in bucket[i])
        {
            res.Add(item);
            if (res.Count == k)
            {
                return res;
            }
        }
    }
    return res;
}

根据字符出现频率排序

leetcode题目地址

public string FrequencySort(string s) {
    int[] map = new int[128];
    IList<char>[] buckets = new IList<char>[s.Length + 1];
    StringBuilder ans = new StringBuilder();

    foreach (char ch in s)
        map[ch]++;

    for (int i = 0; i < map.Length; i++){
        if (buckets[map[i]] == null)
            buckets[map[i]] = new List<char>();
        buckets[map[i]].Add((char) i);
    }

    for (int i = buckets.Length - 1; i > 0; i--){
        if (buckets[i] == null)
            continue;

        foreach (char c in buckets[i]){
            for (int j = 1; j <= i; j++)
                ans.Append(c);
        }
    }

    return ans.ToString();
}

前k个高频单词

leetcode题目地址

public IList<string> TopKFrequent(string[] words, int k) {
    var res = new List<string>();
    var dict = new Dictionary<string, int>();
    foreach(var w in words){
        if(!dict.ContainsKey(w)){
            dict.Add(w, 0);
        }
        dict[w]++;
    }
    var bucket = new List<string>[words.Length];
    for(var i=0;i<bucket.Length;i++){
        bucket[i] = new List<string>();
    }
    
    foreach(var w in dict){
        bucket[w.Value].Add(w.Key);
    }
    
    var count = 0;
    for(var i=bucket.Length-1;i>=0;i--){
        bucket[i].Sort();
        foreach(var w in bucket[i]){
            res.Add(w);
            count++;
            if(count==k) return res;
        }
    }
    
    return res;
}

你可能感兴趣的:(基础算法)