給定 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 []
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能夠使時間複雜度下降到常數階,因此在查詢時更快!算法