MiaoRain / Algorithm_leetcode

0 stars 1 forks source link

LeetCode-hashtable #15

Open MiaoRain opened 4 years ago

MiaoRain commented 4 years ago

image

ans = collections.defaultdict(list)#字典中的值,用list表示
        #ans = {}#普通字典,输入新的key,会报错,上面方式就可以解决
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            #print(count)
            #print(tuple(count))
            ans[tuple(count)].append(s)
            print(ans)#{(1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0): ['eat']})
        return ans.values()
MiaoRain commented 4 years ago

image

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:#nums:[11,15,2,7], target:9
        dic = {}
        for i in range(len(nums)):
            if target-nums[i] not in dic:
                dic[nums[i]] = i
                print(dic)#{11: 0} {11: 0, 15: 1} {11: 0, 15: 1, 2: 2}
            else:
                return [dic[target-nums[i]], i] #[2,3]