给定列表中数字相加求目标和

Question: 给定列表中数字相加求目标和

👉LeetCode链接👈

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.

给定一个 int 类型的数组,返回两个数字相加等于一个指定的目标值时的两个指针。

每个输入只有一个答案,不能使用一个元素两次(不能自己与自己相加等于目标值)。

Example

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def two_sum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
O(n*n-n)
"""
for i, v in enumerate(nums):
diff = target - v
if diff in nums:
if diff == v:
if nums.count(diff) == 1:
continue
else:
v_index = nums.index(v)
nums.remove(v)
diff_index = nums.index(diff)+1
return [v_index, diff_index]
return [nums.index(v), nums.index(diff)]

Finally

之前考虑得太简单了,[3, 3] 6 | [3, 2, 4] 6 | [3, 2, 3] 6 这些情况都没有考虑到