今天是day6:
1 四数相加:给定四个整数数组,长度都为n,计算有多少个元组满足四数字相加为0:
func fourSumCount(nums1 []int,nums2 []int,nums3 []int,nums4 []int) int {
//make创造一个map,键值对都为int
m:=make(map[int]int)
count:=0
// 双层嵌套两值相加统计次数
for _,v1 := range nums1{
for _,v2:= range nums2{
m[v1 + v2]++
}
}
//两层嵌套接着满足加起来为0
for _,v3 := range nums3{
for _,v4:= range nums4 {
count += m[-v3-v4]
}
}
return count
}
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:
hashmap[n1+n2] = hashmap.get(n1+n2,0) +1
count = 0
for n3 in nums3:
for n4 in nums4:
key = -n3-n4
if key in hashmap:
count += hashmap[key]
return count
}
from collections import defaultdict
class Solution:
def fourSumCount(self,nums1:List[int],nums2:List[int],nums3:List[int],nums4:List[int]) -> int{
rec,cnt = defaultdict(lambda:0),0
for i in nums1:
for j in nums2:
rec[i+j] += 1
for i in nums3:
for j in nums4:
cnt+= rec.get(-(i+j),0)
return cnt
}
2 赎金信:判断两个单词的字母组成是否相同:
func canConstruct(ransomNate string,magazine string) bool {
record:= make([]int,26)
for _,v:= range magazine{
record[ v - 'a']++
}
for _,v := range ransomNote{
record[v - 'a']--
if record[v - 'a'] < 0{
return false
}
}
return true
}
class Solution:
def canConstruct(self,ransomNote:str,magazine:str) -> bool:
counts = {}
for c in magazine:
counts[c] = counts.get(c,0) +1
for c in ransomNote:
if c not in counts or counts[c] == 0:
return False
counts[c] == -1
return True
class Solution:
def canConstruct(Self,ransomnote:str,magazine:str) -> bool {
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))
}
3 三数之和:返回三数字相加为0
func threeSum(nums []int) [][]int {
sort.Ints(nums)
res:=[][]int{}
for i:=0;i<len(nums) - 2;i++{
n1:=nums[i]
if n1 >0{
break
}
if i>0 && n1 == nums[i-1] {
continue
}
l,r:=i+1,len(nums) - 1
for l<r{
n2,n3 := nums[l],nums[r]
if n1+n2+n3 ==0{
res = append(res,[]int{n1,n2,n3})
for l<r && nums[l] == n2 {
l++
}
for l < r && nums[r] == n3 {
r--
}
}else if n1+n2+n3 < 0{
l++
}else{
r--
}
}
}
return res
}
class Solution:
def threeSum(self,nums:List[int]) ->List[List[int]]:
result = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
return result
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
四数之和:四个数字相加为0
func fourSum(nums []int, target int) [][]int {
//先排除条件不符合即长度小于四的
if len(nums) <4{
return nil
}
//先将数组整体整数化切片后再升序排序
sort.Int(nums)
var res[][]int
//此处也是为了找出四个元素而遍历
for i:=0;i< len(nums) - 3;i++{
n1 := nums[i]
//此时重复,跳出当前for循环直接开始下一次for循环
if i > 0 && n1 == nums[i -1]{
continue
}
//在第一个for循环的基础上嵌套第二个for则是为了找第二个不重复值
for j:=0;j<len(nums) - 2;j++{
n2:=nums[j]
//逻辑同上
if j > i+1 && n2 == nums[j-1]{
continue
}
//此时前两个数字应该是已经找到了,所以用双指针法来找剩余的两个
l:=j+1
r:=len(nums) -1
for l < r {
n3:=nums[l]
n4:=nums[r]
sum:=n1+n2+n3+n4
//这个逻辑用来不断调整位置最终使得sum=target
if sum < target {
l++
}else if sum > target{
r--
}else{
//此时,把n1,n2,n3,n4追加至res中
res = append(res,[]int{n1,n2,n3,n4})
//此时仍要去重
for l < r && n3 == nums[l+1] {
l++
}
for l < r && n4 == nums[r-1]{
r--
}
r--
l++
}
}
}
}
return res
}
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
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
//空字典与遍历nums的值并将其加入至freq中
freq = {}
for num in nums:
freq[num] = freq.get(num,0) + 1
//声明一个空集合set
ans = set()
//三层内嵌for直接去重
for i in range(len(nums)):
for j in range(i+1,len(nums)):
for k in range(j+1,len(nums)):
//这里直接用val等于三者和与target之差,判断其是否在已有的nums字典中
val = target - (nums[i] + nums[j] + nums[k])
//如果在,那么统计三层嵌套中分别存在的等于val的个数,val就是我们要找的剩下的一个数
if val in freq:
count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val)
//将排序后的一组元素转换为元组,并将该元组添加到 ans 集合
if freq[val] > count:
ans.add(tuple(sorted([nums[i],nums[j],nums[k],val])))
return [list(x) for x in ans]