1. 程式人生 > >1. 兩數之和 雜湊雜湊

1. 兩數之和 雜湊雜湊

給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。

你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

最容易想到的當然是雙層迴圈的暴力解法啦,當然是超時了啊!

下面用散列表的方法來解:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n=len(nums)
        hashtable={}  #建立散列表
        for i in range(n):
            if(target-nums[i] in hashtable):
                return hashtable[target-nums[i]],i
            else :
                hashtable[nums[i]]=i  #散列表填充