思路:先排序,在遍历。排序用快速排序,时间复杂度为
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn),遍历的时间复杂度为
O
(
n
)
O(n)
O(n),总的时间复杂度为
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)。
空间复杂度
O
(
n
)
O(n)
O(n).
执行用时: 52 ms ,超过31%
内存消耗: 13.3 MB,超过42%
class Solution(object):
def quick_sort(self, nums, l, r):
if l<r:
i = l
j = r
k = nums[i]
while(i<j):
# 从右往左
# print(nums)
while nums[j]>=k and i<j:
j -= 1
if i<j:
nums[i] = nums[j]
while nums[i]<=k and i<j:
i += 1
if i<j:
nums[j] = nums[i]
nums[i] = k
self.quick_sort(nums, l ,i-1)
self.quick_sort(nums, i+1 ,r)
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
import copy
newnums = copy.deepcopy(nums)
self.quick_sort(nums, 0, len(nums)-1)
i = 0
j = len(nums)-1
while(i<j):
if nums[i] + nums[j]>target:
j -= 1
if nums[i] + nums[j]<target:
i += 1
if nums[i] + nums[j]==target:
if nums[i]== nums[j]:
return [newnums.index(nums[i]),newnums.index(nums[j],newnums.index(nums[i])+1)]
else:
return [newnums.index(nums[i]),newnums.index(nums[j])]
别人的做法
这个思路和我是一样的,学python这么久了还没有用sorted这个函数,记录一下。
执行用时: 44 ms,超过54%
内存消耗: 14.9 MB,超过23%
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
sort_id = sorted(range(len(nums)), key=lambda k: nums[k])
head = 0
tail = len(nums)-1
result = nums[sort_id[head]] + nums[sort_id[tail]]
while result != target:
if result > target:
tail -= 1
if result < target:
head += 1
result = nums[sort_id[head]] + nums[sort_id[tail]]
return [sort_id[head], sort_id[tail]]
暴力枚举法:拿出一个数字,用target减去它,如果得到的结果在这个数字往后的列表里,那就返回他们的索引值。
执行用时: 28 ms,超过100%
内存消耗: 15 MB,超过14%
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(length):
res = target - nums[i]
if res in nums[i+1:]:
return [i, nums[i+1:].index(res)+i+1]
总结:如果最求速度的话能用内置函数就用内置函数,毕竟官方的代码效率是比绝大部分人都要高的。