两数之和
https://leetcode.cn/problems/two-sum/
解法:哈希表,时间和空间复杂度都是O(n)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashtable = {}
for i, item in enumerate(nums):
if (target - item) in hashtable:
return [hashtable[target-item], i]
hashtable[item] = i
return []
变体:如果不是返回idx,而是返回元素值,可以排序+双指针,O(nlogn)
https://leetcode.cn/problems/3sum/description/
思路:排序 + 双指针
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
if (n < 3):
return []
res = []
nums.sort()
for i in range(n):
if (nums[i] > 0):
return res
# 对nums[i]去重
if (i > 0 and nums[i] == nums[i-1]):
i += 1
continue
L = i+1
R = n-1
while (L < R):
if (nums[i] + nums[L] + nums[R] == 0):
res.append([nums[i], nums[L], nums[R]])
# 对nums[L]去重
while(L < R and nums[L] == nums[L+1]):
L += 1
# 对nums[L]去重
while(L < R and nums[R] == nums[R-1]):
R -= 1
# 移动指针,这步容易忘
L += 1
R -= 1
elif (nums[i] + nums[L] + nums[R] > 0):
R -= 1
else:
L += 1
return res
时间复杂度:O(n2)
空间复杂度: O(1) (取决于排序算法)