leetcode 49. 字母异位词分组 50. 组合总和 II

leetcode 49. 字母异位词分组 50. Pow(x, n)

49. 字母异位词分组

难度中等906收藏分享切换为英文接收动态反馈

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母都恰好只用一次。

示例 1:

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:

输入: strs = [""]
输出: [[""]]

示例 3:

输入: strs = ["a"]
输出: [["a"]]

提示:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] 仅包含小写字母

通过次数247,348

提交次数371,307

# leetcode submit region begin(Prohibit modification and deletion)
import collections
from typing import List


class Solution:


    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        #排序
        result = {}
        for s in strs:
            slen = len(s)
            s_arr = list(s)
            for j in range(slen):
                for k in range(slen):
                    if s_arr[j] > s_arr[k]:
                        s_arr[j], s_arr[k] = s_arr[k], s_arr[j]
            appstr = "".join(s_arr)
            if appstr not in result:
                result[appstr] = [s]
            else:
                result[appstr].append(s)
        return list(result.values())

    def groupAnagrams2(self, strs: List[str]) -> List[List[str]]:
        mp = collections.defaultdict(list)
        for st in strs:
            counts = [0] * 26
            for ch in st:
                counts[ord(ch) - ord("a")] += 1
            # 需要将 list 转换成 tuple 才能进行哈希
            mp[tuple(counts)].append(st)

        return list(mp.values())
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
    strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    # strs = ["", ""]
    # strs = ["","b"]
    # strs = ["ant","ant"]
    strs = ["", "b", "", "ant", "ant","eat", "tea", "tan", "ate", "nat", "bat"]
    strs = ["ac","c"]
    print(Solution().groupAnagrams(strs))

50. Pow(x, n)

难度中等787收藏分享切换为英文接收动态反馈

实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。

示例 1:

输入:x = 2.00000, n = 10
输出:1024.00000

示例 2:

输入:x = 2.10000, n = 3
输出:9.26100

示例 3:

输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25

提示:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • -104 <= xn <= 104

通过次数228,883

提交次数608,850

# 实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x⁴
# 
#  Related Topics 递归 数学 
上一篇:windows xp能连上网但是不能上网的解决办法


下一篇:一文看尽HashMap