兩數(shù)之和
給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會(huì)對應(yīng)一個(gè)答案。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
1、
class Solution:
def twoSum(self, nums: List[int], target: int):
for i in nums:
j = target - i
start_index = nums.index(i)
next_index = start_index + 1
temp_num = nums[next_index:]
if j in temp_num:
return [nums.index(i), next_index + temp_num.index(j)]
2、
class Solution(object):
def twoSum(self, nums, target):
# 定義字典
num_dict = {}
len_nums = len(nums)
# 遍歷列表
for i in range(len_nums):
temp = target - nums[i]
if temp not in num_dict:
num_dict[nums[i]] = i
else:
return [num_dict[temp], i]
我不生產(chǎn)程序,我只是程序的搬運(yùn)工