刷题日记(6/60)

454 四数相加

给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:

class Solution(object):
    def fourSumCount(self, nums1, nums2, nums3, nums4):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type nums3: List[int]
        :type nums4: List[int]
        :rtype: 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

总结:具体思路为,分A+B和C+D两组,现将A+B中可能出现的值放入哈希表内(Python中即为字典),然后计算C+D,将可能出现的值与A+B中的值进行对比,若之和为0,则计数器count的数量增长hashmap[key]个,原因是不考虑重复的情况。

383赎金信

给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。

如果可以,返回 true ;否则返回 false 。

magazine 中的每个字符只能在 ransomNote 中使用一次。

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        arry = [0]*26
        for x in magazine:
            arry[ord(x)-ord("a")] += 1
        for i in ransomNote:
            arry[ord(i)-ord("a")] -= 1
        for j in arry:
            if j < 0:
                return False
        return True

总结:唯一要注意的一点是,magzine可以比ransomNote的字母多

15三数之和:

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。

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

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        #python中数组自带的排序函数sort,sorted,区别在于,sorted并没有改变sorted的原数组,而是需要一个新数组存放排序后的数组
        #而sort则是直接修改了原数组
        result = []
        nums.sort()
        for i in range(len(nums)):
            if nums[i]>0:#如果数组第一个就大于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


总结:采用“三指针”,其实是双指针,i用于遍历,left和right作为双指针,主要需要注意的部分是,去重操作,因为题目中要求不可以重复

18 四数之和

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。

class Solution:
    def fourSum(self, nums, target):
        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

四数之和也就是在三数之和的基础上多了一层嵌套,需要注意的地方还是一样,例如去重

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值