1.原文题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2.解题思路
遍历数组 a,然后看除了
a数组中有没有 target-a 的数,这样就能保证该数组有两个数和等于 target;但是时间复杂度为 O(n2)
可以借用哈希(Python 叫字典),我们遍历元素的时候,且记录元素的下标,当我们找 target-a 时候,只需要在字典找,就可以了,查找字典时间复杂度为 O(1)。
3.Python代码
# -*- coding: utf-8 -*-
# @Time : 2019/5/12 9:01
# @Author : ZXL
# @Site :
# @File : 1.两数之和.py
# @Software: PyCharm
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_length = len(nums)
for one_num in range(nums_length - 1):
for second_num in range(one_num + 1, nums_length):
if nums[one_num] + nums[second_num] == target:
return [one_num, second_num]
if __name__ == '__main__':
nums = [2,2,3,6,7, 11, 15]
target = 9
solution = Solution()
result = solution.twoSum(nums, target)
print(result)
class Solution1(object):
# 可用一遍遍历,即根据当前遍历得到的元素index,
# 查找target-index是否在剩余数组里出现
# 如果找得到,则返回其下标值;反之则说明没有该答案
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
answer = []
for left_index in range(len(nums)):
right = target - nums[left_index]
if right in nums[left_index+1:]:
nums_right = nums[left_index+1:]
right_index = nums_right.index(right)+left_index+1
answer.extend([left_index, right_index])
return answer
if __name__ == "__main__":
nums = [-1, -2, -3, -4, -5, -6]
target = -8
answer = Solution1().twoSum(nums, target)
print(answer)
class Solution3:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
lookup = {}
for i in range(n):
tmp = target - nums[i]
if tmp in lookup:
return [lookup[tmp], i]
lookup[nums[i]] = i
if __name__ == "__main__":
nums = [-1, -2, -3, -4, -5, -6]
target = -8
answer = Solution3().twoSum(nums, target)
print(answer)