所用語言:python
題目:給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,并返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重復利用這個數組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權歸領扣網絡所有。商業(yè)轉載請聯系官方授權,非商業(yè)轉載請注明出處。
解法1:使用兩個循環(huán)嵌套,逐個遍歷數組,將符合的條件記錄下來
class Solution(object):
? ? def twoSum(self, nums, target):
? ? ? ? """
? ? ? ? :type nums: List[int]
? ? ? ? :type target: int
? ? ? ? :rtype: List[int]
? ? ? ? """
? ? ? ? a=list()
? ? ? ? for i in range(len(nums)):
? ? ? ? ? ? for j in range(i+1,len(nums)):
? ? ? ? ? ? ? ? if nums[i]+nums[j]==target:
? ? ? ? ? ? ? ? ? ? return i,j
解法二:使用python中的‘in’條件語句:
class Solution(object):
? ? def twoSum(self, nums, target):
? ? ? ? """
? ? ? ? :type nums: List[int]
? ? ? ? :type target: int
? ? ? ? :rtype: List[int]
? ? ? ? """
? ? ? ? for i in range(len(nums)):
? ? ? ? ? ? a=target-nums[i]
? ? ? ? ? ? if a in nums and nums.index(a)!=i:
? ? ? ? ? ? ? ? return i,nums.index(a)
解法三,使用字典查找:
class?Solution(object):
????def?twoSum(self,?nums,?target):
????????"""
????????:type?nums:?List[int]
????????:type?target:?int
????????:rtype:?List[int]
????????"""
????????hashmap={}
????????for?i,num?in?enumerate(nums):
????????????#if?hashmap.get(target?-?num)?is?not?None:
????????????if?target-num?in?hashmap:
????????????????return?i,hashmap[target-num]
???????????????#?return?i,hashmap.get(target-num)
????????????hashmap[num]?=?i?#這句不能放在if語句之前,解決list中有重復值或target-num=num的情況
??????????????????????????????????? 解法一?????????????????? 解法二?????????????????? 解法三
?執(zhí)行用時|內存消耗??? 3852ms|12,5MB???? 976ms|12.4MB??? 28ms|13.1MB