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.

1
2
3
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路

因为题目给出的数组当中一定会有且只有一个解,而且不能重复用一个元素。所以第一层循环用以遍历数组中的元素,第二层循环用以查询此元素之后,是否还有元素满足要求。

因为这一题的难度是easy,所以利用上面所说,类似于穷举的方法就可以直接得到结果,不需要考虑额外的时间复杂度。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
for i in range(length):
remain = target - nums[i]
for j in range(i+1, length):
if (nums[j] == remain):
return [i, j]