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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解析:给定一个整数数组,返回可以相加等于目标的元素下标。
解题思路:1.蛮力法
代码:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
List=[]
k=len(nums)
for i in range(k):
for j in range(i+1,k):
if nums[i]+nums[j]==target:
List.append(i)
List.append(j)
return List
2.hashtable
代码:
def twoSum(self, nums, target):
index = {}
for i, x in enumerate(nums):
if target - x in index:
return [index[target - x], i]
index[x] = i