leetcode454 四数相加 ||
字典法
先计算n1 + n2,将其和制成一个字典;然后计算-n3-n4是否在字典中。
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
if n1 + n2 in hashmap:
hashmap[n1+n2] += 1
else:
hashmap[n1+n2] = 1
count = 0
for n3 in nums3:
for n4 in nums4:
key = -n3 - n4
if key in hashmap:
count += hashmap[key]
return count
leetcode 383 赎金信
collections库方法(Counter)
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine):
return False
return not collections.Counter(ransomNote) - collections.Counter(magazine)
哈希表法
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine):
return False
ransom_count = [0] * 26
magazine_count = [0] * 26
for c in ransomNote:
ransom_count[ord(c) - ord('a')] += 1
for c in magazine:
magazine_count[ord(c) - ord('a')] += 1
return all(ransom_count[i] <= magazine_count[i] for i in range(26))
leetcode15 三数之和
初步思路是通过哈希表法确定第三个数,但是题目中的不重复无法满足
本题的指导思路首先是双指针法,其次在去重的时候代码应该是‘if i > 0 and nums[i] == nums[i - 1]:’,因为我们需要去重的是相同的三元组而不是组内相同的数。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
ans = []
if n < 3:
return ans
nums.sort()
for i in range(n):
if nums[0] > 0:
return ans
if i > 0 and nums[i] == nums[i-1]:
continue
l,r = i+1,n-1
while(l<r):
sum = nums[i] + nums[l] + nums[r]
if sum == 0:
ans.append([nums[i],nums[l],nums[r]])
while l < r and nums[r] == nums[r-1]:
r -= 1
while l < r and nums[l] == nums[l+1]:
l += 1
l += 1
r -= 1
elif sum > 0:
r -= 1
else:
l += 1
return ans
leetcode18 四数之和
四数之和和三数之和有些相似,不同的是需要再三数之和外围加一个for循环。同时由于四数之和中要求四数不重复,所以需要再循环前后加边界判断
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n = len(nums)
ans = []
nums.sort()
if n < 4 or not nums:
return ans
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
l, r = j + 1, n - 1
while l < r:
sum = nums[i] + nums[j] + nums[l] + nums[r]
if sum == target:
ans.append([nums[i],nums[j],nums[l],nums[r]])
while l < r and nums[l] == nums[l+1]:
l += 1
while l < r and nums[r] == nums[r-1]:
r -= 1
l += 1
r -= 1
elif sum > 0:
r -= 1
else:
l += 1
return ans