题目地址:https://leetcode.com/problems/two-sum/description/
Tag: Array
Difficulty: easy

题目描述

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:

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

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

解题思路

用一层for循环遍历nums数组中的元素x,令k = target-x,用in判断k是否在nums数组中,如果在,返回x和k

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
k = target - nums[i]
if k in nums and i != nums.index(k):
index = nums.index(k)
return [i,index]

第10行,i != nums.index(k)是为了防止nums=[3,3], target=6这样的情况,需要过滤掉k和nums[i]处在同一个位置。

第二种思路还有另一种实现方法,通过字典构建一个哈希表:

1
2
3
4
5
6
7
8
class Solution:
def twoSum(self, nums, target):
dic = {}
for i,num in enumerate(nums):
if num in dic:
return [dic[num],i]
else:
dic[target-num] = i

在Discuss区还看到一种清奇的实现方法,代码地址

1
2
3
4
5
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)-1,0,-1):
if target-nums[i] in nums[:i]:
return [nums.index(target-nums[i]),i]