一、四数相加 II
leetcode 454 四数相加 II
思路:
把前两个数组的和放到哈希表中,然后再两个for循环进行一个哈希表的匹配,时间复杂度是O(n^2)
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap_first2_sum, hashmap_last2_sum = {}, {}
n = len(nums1)
result = 0
for i in range(n):
for j in range(n):
sum_i_j = nums1[i] + nums2[j]
if sum_i_j in hashmap_first2_sum.keys():
hashmap_first2_sum[sum_i_j] += 1
else:
hashmap_first2_sum[sum_i_j] = 1
for i in range(n):
for j in range(n):
need_num = 0 - nums3[i] - nums4[j]
if need_num in hashmap_first2_sum.keys():
result += hashmap_first2_sum[need_num]
return result
二、赎金信
leetcode 383 赎金信
简单题,存内容到hashmap里面然后去判断即可
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hashmap = collections.defaultdict(int)
for ransom_str in ransomNote:
hashmap[ransom_str] += 1
for magazine_str in magazine:
if hashmap[magazine_str] > 0:
hashmap[magazine_str] -= 1
for key in hashmap.keys():
if hashmap[key] > 0:
return False
return True
三、三数之和
leetcode 15 三数之和
思路:利用hashmap的额外空间来代替第三层的for循环,从而将时间复杂度减少到O(n^2)
如何实现不重复呢?
解决方案:对nums进行排序,然后在第一和第二次循环过程中维护一个
p
r
e
i
pre_i
prei和
p
r
e
j
pre_j
prej变量,用于存储之前已经遍历过的情况,防止结果的重复
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
hashmap = {}
result = []
nums_len = len(nums)
nums = sorted(nums)
for i in range(nums_len):
if nums[i] not in hashmap.keys():
hashmap[nums[i]] = [i]
else:
hashmap[nums[i]].append(i)
print(hashmap)
pre_i = inf
for i in range(nums_len - 2):
if nums[i] == pre_i:
continue
pre_i = nums[i]
pre_j = inf
for j in range(i + 1, nums_len - 1):
if nums[j] == pre_j:
continue
pre_j = nums[j]
find_elem = 0 - nums[i] - nums[j]
if find_elem not in hashmap.keys():
continue
else:
for k in hashmap[find_elem]:
if k > j:
result.append((nums[i], nums[j], nums[k]))
break
else:
continue
return result
四、四数之和
leetcode 18 四数之和
和第三题一样的思路
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
hashmap = {}
num_len = len(nums)
nums = sorted(nums)
result = []
for i in range(num_len):
if nums[i] in hashmap.keys():
hashmap[nums[i]].append(i)
else:
hashmap[nums[i]] = [i]
pre_a = inf
for a in range(num_len - 3):
if nums[a] == pre_a:
continue
pre_a = nums[a]
pre_b = inf
for b in range(a + 1, num_len - 2):
if nums[b] == pre_b:
continue
pre_b = nums[b]
pre_c = inf
for c in range(b + 1, num_len - 1):
if nums[c] == pre_c:
continue
pre_c = nums[c]
need_num = target - nums[a] - nums[b] - nums[c]
if need_num in hashmap.keys():
for d_index in hashmap[need_num]:
if d_index > c:
result.append([nums[a], nums[b], nums[c], need_num])
break
else:
continue
else:
continue
return result