LeetCode #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].
题目(中)
给定一个整数数组 nums
和一个目标值target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
solution 1: 设value用list.index(value)
求index
解法1的核心思想是先遍历给定nums
列表(list)中的所有元素,每次遍历我们都会生成一个字列表temp_nums
,然后看j
在不在temp_nums
里,在的话返回当前循环i
的index
和 找到的j
的index
。
注意:
- 这里的
i
和j
代表的都是list
中的value
,所以我们要注意用list.index(value)
返回value
对应的index
- 之所以不用
return [nums.index(i),nums.index(j)]
是因为这道题虽然规定了唯一解的假定,但是index只能用1次,举个例子:nums = [2,2] , target = 4, 返回就是[0,1]。但是如果我们是直接到原list中找的话就会出现问题,因为对于重复的元素list.index(value)
返回的总是第一个遍历到的,所以返回的就是 [0,0] 无法通过测试。于是我们就需要借助temp_nums
来避免这个问题,所以我们在代码中的next_index
是在start_index
的基础上 +1。然后返回值的时候next_index
因为已经加过1了,正好和temp_nums.index(j)
里从0开始相抵消,返回的就是正确的index。 - 如果没有找到target的话,我们是没有return的。
具体代码如下:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Solution 1
for i in nums:
j = target - i
start_index = nums.index(i)
next_index = start_index + 1
temp_nums = nums[next_index:]
if j in temp_nums:
#return [nums.index(i),nums.index(j)]
#这个要是有两个一样的数就会出问题
return [nums.index(i),next_index + temp_nums.index(j)]
solution 2: 设index 用list[index]
/dict{index}
求value
解法2的核心是利用dictionary
的key-value pair
,对于代码的理解我们先用题干案例(nums = [2, 7, 11, 15], target = 9)过一遍:
- 首先
i
= 0,target-nums[0]
= 9 -2 = 7 不在创建的 dict({ }) 中,于是有dict[nums[i]] = i
,即 dict[nums[0]] = dict[2] = 0。dict = {2:0} - 接着
i
= 1,target-nums[1]
= 9 -7 = 2 在创建的 dict({2:0}) 中,于是返回 [dict[9-7],1] = [0,1]
这里注意:
- 这里的
i
跟解法1不同,代表的不是value
,而是index
,所以在创建循环时我们使用的range(len(nums))
而不是nums
。 return [dict[target-nums[i]],i]
也可以写成return [i,dict[target-nums[i]]]
都可以通过测试。
具体代码如下:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# solution 2
dict = {}
for i in range(len(nums)):
if target-nums[i] not in dict:
dict[nums[i]] = i
else:
return [dict[target-nums[i]],i]
总结
- 关于list/tuple/dict 的问题核心就是 index 和 value 的对应
- 注意特殊情况:出现 相等值 / 空 等