【leetcode】兩數之和

 
題目中文
  
  給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個整數,並返回他們的數組下標。
  你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。
 
  示例:
 
給定 nums = [2, 7, 11, 15], target = 9
由於 nums[0] + nums[1] = 2 + 7 = 9,因此返回 [0, 1]

   

算法實現
 
 
第一種:暴力匹配算法
 

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) < 2:
            return []

        iLen = len(nums)
        for i in range(iLen):
            for j in range(i + 1, iLen):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []

 


 
第二種:經過hash的方式
 

 

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) < 2:
            return []

        iLen = len(nums)
        hashDict = {}
        for i in range(iLen):
            find = target - nums[i]
            if find in hashDict:
                return [hashDict[find], i]
            else:
                hashDict[nums[i]] = i
        return []

 

 

 

因爲hash能夠使時間複雜度下降到常數階,因此在查詢時更快!算法

 

 
推薦
相關文章
相關標籤/搜索