leetcode Day1 Two Sum 两数之和
题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given
nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
中文意思就是,给定输入一个列表和一个目标数, 输出的是两个数的下标,这个数的对应的值相加,等于目标数。
上代码:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given
nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
中文意思就是,给定输入一个列表和一个目标数, 输出的是两个数的下标,这个数的对应的值相加,等于目标数。
上代码:
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
indics=[]
for i in range(len(nums)-1):
#使用两次循环,类似于冒泡算法,尝试每个数和另外一个数的和,枚举
for j in range(i+1,len(nums)):
if target== nums[i]+nums[j]:
indics.append(i)
indics.append(j)
return indics