代码随想录算法训练营第七天 | 454.四数相加II、15.三数之和、 18. 四数之和

总结

  1. 什么时候用哈希什么时候不用哈希:一般情况下,求一个数组里面的元素相加,又要去重,用哈希就比较困难,哈希的本质是快速找到一个元素是否在集合里出现过,即一种无序操作。

454 四数相加

题目链接:

leecode_四数相加

自己想
看完题解

1.题解和自己想的一样,都是两个数两个数为一组,然后求和,映射到map()函数中(在python中就是dict)
2.有两个细节,这道题并不需要求的下标是多少,只需要知道有几种情况满足即可,因此只需要dict[sum] +=1;同时不需要去重,因此用哈希更合适

完整代码
class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        dict_1 = {}
        dict_2 = {}
        for index_1,num_1 in enumerate(nums1):
            for index_2, num_2 in enumerate(nums2):
                sum = num_1 + num_2
                # index =[index_1,index_2]
                if sum in dict_1.keys():
                    # dict_1[sum].append(index)
                    dict_1[sum] += 1
                else:
                    dict_1[sum] = 1
                    # dict_1[sum] = []
                    # dict_1[sum].append(index)
        # print(dict_1)
        for index_3,num_3 in enumerate(nums3):
            for index_4, num_4 in enumerate(nums4):
                sum = num_3 + num_4
                # index = [index_3,index_4]
                if sum in dict_2.keys():
                    dict_2[sum] += 1
                    # dict_2[sum].append(index)
                else:
                    dict_2[sum] = 1
                    # dict_2[sum] = []
                    # dict_2[sum].append(index)
        # print(dict_2)
        y2 = 0
        for value in dict_1.keys():
            if - value in dict_2.keys():
                # print(dict_1[value])
                # print(dict_2[-value])
                # y1 = len(dict_1[value]) *len(dict_2[-value])
                y1 = dict_1[value] * dict_2[-value]
                # print(y1)
                y2 += y1

        return y2

15 三数之和

题目链接:

leecode_三数之和

自己想

1.三数之和要求去重,同时三个数在一个数组里,因此

看完题解

1.在同一个数组里,又要去重,因此推荐使用双指针
2.如何去重a, 用if nums[i] == nums[i-1],如何去重b,c,用while

思路衔接

1.要先排序,然后 left = i + 1,有点像滑动窗口
2.什么时候用if 什么时候用while

知识点

在多重while嵌套结构中使用break,会退出距离break最近的那一层while循环,且多从if嵌套对break无约束作用,会跳出最外层if,寻找与之最近的最内层while跳出。
continue:多从if嵌套对continue无约束作用,会跳出最外层if,寻找与之最近的最内层while,然后进行下一步。

完整代码
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        left = 1
        right = n-1
        nums = sorted(nums)
        final_result = []
        for i in range(n):#
            left = i + 1
            right = n - 1
            if nums[i] > 0:
                break
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            while(left < right):
                result = nums[i] + nums[left] + nums[right]
                if result > 0:
                    right -= 1
                elif result < 0:
                    left += 1
                else:
                    final_result.append([nums[i],nums[left],nums[right]])
                    while left != right and nums[right] == nums[right - 1]: right -= 1
                    while left != right and nums[left] == nums[left + 1]: left += 1
                    right -= 1
                    left += 1

        
        return final_result

15 四数之和

题目链接:

leecode_四数之和

自己想
看完题解

1.四数之和就是三数的一个拓展,其实本质就是多一层循环
2.当给出目标值是target时候,就要考虑是否为负数,和三数之和有什么不同的地方呢,主要是在break时,即剪枝的时候要注意

思路衔接

1.要先排序,然后 left = i + 1,有点像滑动窗口
2.什么时候用if 什么时候用while

知识点

在多重while嵌套结构中使用break,会退出距离break最近的那一层while循环,且多从if嵌套对break无约束作用,会跳出最外层if,寻找与之最近的最内层while跳出。
continue:多从if嵌套对continue无约束作用,会跳出最外层if,寻找与之最近的最内层while,然后进行下一步。

完整代码
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        nums = sorted(nums)
        ans = []
        for i in range(n):
            if nums[i] > target and nums[i] > 0:
                break
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            for j in range(i + 1,n):
                left = j + 1
                right = n - 1
                if nums[j] + nums[i] > target and nums[j] + nums[i] > 0:
                    break
                if j > i + 1 and nums[j] == nums[j - 1]:
                    continue

                while(left < right):
                    result = nums[i] + nums[j] + nums[left] +nums[right]
                    if  result < target:
                        left += 1
                    elif result > target:
                        right -= 1
                    else: 
                        ans.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
                                
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值