(LeetCode)哈希表

1. 兩數之和

1. two-sum
在這裏插入圖片描述

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]

        笨辦法
            暴力求解
        
        聰明辦法
            利用dict存儲
        """
        d = {}
        for i, num in enumerate(nums):
            if num not in d:
                d[num] = []
            d[num].append(i)
        for i, num in enumerate(nums):
            if target - num not in d:
                continue
            for j in d[target-num]:
                if i == j:
                    continue
                return [i, j]

2. 字母異位詞分組

49. group-anagrams
在這裏插入圖片描述

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]

        思路
            使用輔助字典,
            key爲異位詞重排序後的字符串, value爲當前key的所有異位詞
        """
        dic = {}

        for anagram in strs:
            key = ''.join(sorted(anagram))
            if key not in dic:
                dic[key] = []
            dic[key].append(anagram)
        
        return list(dic.values())
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章