题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法一:首先最容易想到的就是暴力解法:
时间复杂度O(n^2)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(len(nums)):
if (nums[i] + nums[j] == target):
return [i, j]
解法二:想到了指针的首尾查找,一个头指针和一个尾指针分别指向数组的首尾位置,两数之和大于target,尾指针前移,两数之和小于target,头指针后移,直到等于target,这种方法数组首先需要排序
问题:排序后的数组的下标就不一样了,一开始想到的是使用字典保存原始数组的下标和值,查找到之后就返回原数组的下标,然后发现字典的key不允许重复,如果数组中有重复值,比如nums = [2, 2, 1],保存到字典中之后只剩下一个值了,该方法不可取。
解决:只排序原数组的下标,使用 sorted_id 解决
时间复杂度:O(nlogn)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sorted_id = sorted(range(len(nums)), key=lambda x:nums[x])
# print(sorted_id)
i = 0
j = len(nums) - 1
num_result = nums[sorted_id[i]] + nums[sorted_id[j]]
while num_result != target:
if (num_result < target):
i += 1
elif (num_result > target):
j -= 1
num_result = nums[sorted_id[i]] + nums[sorted_id[j]]
return [sorted_id[i], sorted_id[j]]
解法三:直接用字典做,another_value = target - value
时间复杂度O(n)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict1 = {}
for i, value in enumerate(nums):
another_value = target - value
if another_value in dict1:
return [dict1[another_value], i]
dict1[value] = i
ps:就算是简单的题也有值得思考学习的解法~继续加油!