题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15] ,target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路一
- 时间复杂度为O(n^2)
- 顺序遍历数组, i i i从第一个数开始,找与它相加得到target值的 j j j,而 j j j从 i + 1 i+1 i+1到最后一个数。从而遍历整个数组。
- 缺点:数组中若存在值就是target的情况时处理不能;效率太低,仅仅击败了14%滴小盆友。
思路二
- 时间复杂度为O(n)
- 用hashmap的思想,用字典记录每一个键值对,通过一次便利即可找到所要的值。
思路二
- 时间复杂度为O(n)
- 二分法的思想
代码实现
- 思路一代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i+1,j+1]
- 思路二代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {}
for index,num in enumerate(numbers):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num]+1,index+1]
else:
hashmap[num] = index
- 思路三代码
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
start = 0
end = len(numbers) - 1
while start < end:
temp = numbers[start] + numbers[end]
if temp < target:
start += 1
if temp > target:
end -= 1
if temp == target:
return [start+1,end+1]
2019年4月4日 于燕园北