刷题链接:力扣-两数之和
题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
我的解法:
先排序,再双指针法,当首尾两数之和大于target时,右指针左移,反之左指针右移。
import copy
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp = copy.copy(nums)
temp.sort()
while True:
if len(temp)==1:
break
if (temp[0] + temp[-1]) == target:
num1 = nums.index(temp[0])
num2 = nums.index(temp[-1])
if num1 == num2:
nums.pop(num1)
num2 = nums.index(temp[-1])+1
return [num1, num2]
elif (temp[0] + temp[-1]) > target:
temp.pop(-1)
continue
else:
temp.pop(0)
continue
return [-1,-1]
提交结果:
执行用时:24ms 94.10% 内存消耗:12.6MB 99.23%
优化后的代码:减少删除操作
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp = sorted(nums)
num1 = 0
num2 = len(temp)-1
while True:
if temp[num1] == temp[num2]:
break
if (temp[num1] + temp[num2]) == target:
return [nums.index(temp[num1]), nums.index(temp[num2])]
elif (temp[num1] + temp[num2]) > target:
num2 -= 1
continue
else:
num1 += 1
continue
a = nums.index(temp[num1])
nums[nums.index(temp[num1])] = temp[num1] - 1
return [a, nums.index(temp[num1])]
提交结果:
执行用时: 12ms 99.61% 内存消耗:12.5MB 99.76%
时间复杂度:排序O(nlogn),遍历O(n)
别人的方法:
直接查找。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
r_nums={}
for index,num in enumerate(nums):
jieguo = target - num
if jieguo in r_nums:
return [r_nums[jieguo],index]
r_nums[num] = index
return 0
有个思想,尽量不处理用不到的数据。
当在待查数组里没有找到差值时,就把自己加入待查数组。这样可以在最好情况下极大的减少时间消耗。Python内置方法的时间复杂度:查找 O(n),排序O(nlogn)。所以该方法的最差情况为O(n^2)。