題目中文
給定一個整數數組 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可以使時間復雜度降低到常數階,所以在查詢時更快!
推薦

喜歡編程
浙公網安備 33010602011771號