赞
踩
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
import collections
hashmap = collections.defaultdict(int)
for i in nums1:
for j in nums2:
hashmap[i+j] += 1
res = 0
for i in nums3:
for j in nums4:
key = -i-j
if key in hashmap.keys():
res += hashmap[key]
return res
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hashmap = [0]*26
for i in magazine:
hashmap[ord(i)-97] += 1
for i in ransomNote:
hashmap[ord(i)-97] -= 1
if hashmap[ord(i)-97]<0:
return False
return True
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() N = len(nums) res = [] for ind,target in enumerate(nums): if target>0: return res if ind>0 and target == nums[ind-1]: ## ind>0是需要把[0,0,0]包含进来 第一个数去重 continue left,right = ind+1,N-1 while(left<right): total = nums[left] +nums[right] if total > -target: right -= 1 elif total < -target: left += 1 else: res.append([target,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 return res
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: res = [] nums.sort() n = len(nums) for i in range(n-3): if i>0 and nums[i]==nums[i-1]: continue for j in range(i+1,n-2): if j>i+1 and nums[j]==nums[j-1]: continue left,right = j+1,n-1 while(right>left): temp = target-(nums[i]+nums[j]) if nums[left]+nums[right]>temp: right -= 1 elif nums[left]+nums[right]<temp: left += 1 else: res.append([nums[i],nums[j],nums[left],nums[right]]) while(left<right and nums[left+1]==nums[left]): left += 1 while(left<right and nums[right-1]==nums[right]): right -= 1 left += 1 right -= 1 return res
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。