欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode-哈希表

程序员文章站 2022-06-23 18:36:55
...
  • 查询时间复杂度:O(1)

451. 根据字符出现频率排序

class Solution(object):
    def frequencySort(self, s):
        dic = {c:s.count(c) for c in set(s)}
        ret = sorted(dic.items(), key = lambda x:x[1], reverse = True)
        return ''.join([x[0] * x[1] for x in ret])

49. 字母异位词分组

class Solution(object):
    def groupAnagrams(self, strs):
        res = []
        dic = {}
        for s in strs:
            keys = "".join(sorted(s))
            if keys not in dic:
                dic[keys] = [s]
            else:
                dic[keys].append(s)
                
        return list(dic.values())

347. 前 K 个高频元素

class Solution(object):
    def topKFrequent(self, nums, k):
        dic = {c:nums.count(c) for c in set(nums)}
        ret = sorted(dic.items(),key = lambda x:x[1], reverse = True)
        return [i[0] for i in ret][:k]