题目:
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].
思路 & 代码:
两层循环,i from 0 to n-1, j from i+1 to n-1,遍历找到 nums 中对应数的和为target的数,将 i,j 保存在列表 result 中,返回 result 。
class Solution:
def twoSum(self, nums, target):
n = len(nums)
result = []
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
result.append(i)
result.append(j)
return result
sol = Solution()
nums = [2, 7, 9, 11]
target = 9
print(sol.twoSum(nums, target))