赞
踩
15和18题其实不是哈希表,是双指针,要考虑去重的细节。
454题 四数相加2
思路:四个数组,两两一组,把a+b的值和个数存入字典(即哈希表),即 counter[sum] =counter.get(sum, 0) + 1。如果 -(c+d)的值=a+b,则把计数器res += a+b对应的个数。
class Solution(object): def fourSumCount(self, nums1, nums2, nums3, nums4): counter = dict() for i in nums1: for j in nums2: sum = i + j counter[sum] = counter.get(sum, 0) + 1 res = 0 for i in nums3: for i in nums4: sum2 = -i - j if sum2 in sum: res += counter[sum2] return res
383题 赎金信
方法一:字典 class Solution(object): def canConstruct(self, ransomNote, magazine): counts = dict() for i in magazine: counts[i] = counts.get(i, 0) + 1 for c in ransomNote: if c not in counts or counts[c] == 0: return False counts[c] -= 1 return True 方法二:Counter 只有当counter1中的键值对含在counter2里时,相减会返回{}空字典,即为False,not False为True class Solution(object): def canConstruct(self, ransomNote, magazine): from collections import Counter return not Counter(ransomNote) - Counter(magazine) 方法三:数组 class Solution(object): def canConstruct(self, ransomNote, magazine): ransom_count = [0] * 26 magazine_count = [0] * 26 for i in ransomNote: ransom_count[ord(i) - ord('a')] += 1 for j in magazine: magazine_count[ord(j) - ord('a')] += 1 return all(ransom_count[i] <= magazine_count[i] for i in range(26)) return all 即 当all后面所有的例子都成立,返回True,反之。
15题 三数之和
不是哈希表,用双指针(其实是三指针) 难点:去重 注意:while right > left and nums[right] == nums[right - 1]: while right > left and nums[left] == nums[left + 1]: 这两句里面的right>left不可省略,不然会出现如[0,0,0]这个案例,right一直向左移,移到第一个0,后面right-=1,就会报错。不是说在大循环里有了的条件,在小循环里就可以省略不写了。
class Solution(object): def threeSum(self, nums): nums.sort() result = [] for i in range(len(nums)): if nums[i] > 0: break if i >0 and nums[i] == nums[i - 1]: continue left = i + 1 right = len(nums) - 1 while right > left: sum = nums[i] + nums[left] + nums[right] if sum < 0: left += 1 elif sum > 0: right -= 1 else: result.append([nums[i] , nums[left], nums[right]]) while right > left and nums[right] == nums[right - 1]: right -= 1 while right > left and nums[left] == nums[left + 1]: left += 1 right -= 1 left += 1 return result
18题 四数之和
- class Solution:
- def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
- nums.sort()
- n = len(nums)
- result = []
- for i in range(n):
- if nums[i] > target and nums[i] > 0 and target > 0:# 剪枝(可省)
- break
- if i > 0 and nums[i] == nums[i-1]:# 去重
- continue
- for j in range(i+1, n):
- if nums[i] + nums[j] > target and target > 0: #剪枝(可省)
- break
- if j > i+1 and nums[j] == nums[j-1]: # 去重
- continue
- left, right = j+1, n-1
- while left < right:
- s = nums[i] + nums[j] + nums[left] + nums[right]
- if s == target:
- result.append([nums[i], nums[j], nums[left], nums[right]])
- while left < right and nums[left] == nums[left+1]:
- left += 1
- while left < right and nums[right] == nums[right-1]:
- right -= 1
- left += 1
- right -= 1
- elif s < target:
- left += 1
- else:
- right -= 1
- return result
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。