代码随想录Day7

454.四数相加II

给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。

class Solution(object):
    def fourSumCount(self, nums1, nums2, nums3, nums4):
   
        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

四数相加,使用字典为hashmap;四个数组中A[i]+B[j]+C[k]+D[l]=0,两个for循环解决,第一个for循环遍历AB数组,将A[i]+B[j]放进hashmap;第二个for循环遍历CD数组将-(C[k]+D[l])和hashmap对比。

383. 赎金信

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

方法一

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        ransomNote_count=[0]*26
        magazine_count=[0]*26
        for c in ransomNote:
          ransomNote_count[ord(c)-ord("a")] += 1
        for c in magazine:
          magazine_count[ord(c) - ord('a')] += 1
        return all(ransomNote_count[i]<=magazine_count[i] for i in range(26))

使用数组作为hashmap,字母的ascll码值作索引和比较。

方法二

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

使用字典作为哈希表。

第15题. 三数之和

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

注意: 答案中不可以包含重复的三元组。

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: 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:
                    right-=1
                elif sum_<0:
                    left+=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题. 四数之和

题意:给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        result=[]
        nums.sort()
        for i in range(len(nums)):
            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,len(nums)):
                if nums[i] + nums[j] > target and target > 0: 
                    break             
                if j>i+1 and nums[j]==nums[j-1]:
                    continue
                left=j+1
                right=len(nums)-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
                # while right>left:
                #     sum_=nums[i]+nums[j]+nums[left]+nums[right]                       
                #     if sum_>target:
                #         right-=1
                #     elif sum_<target:
                #         left+=1
                #     elif sum_==target:
                #         result.append([nums[i],nums[j],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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值