if(分支)语句的执行效率分析

if(分支)语句的执行效率分析

问题描述:

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

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

解法

解法一:

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
        """
        dic = dict()
        # 两两一组
        for i in nums1:
            for j in nums2:
                if i+j not in dic.keys():
                    dic[i+j] = 1
                else:
                    dic[i+j] += 1
        count = 0
        for i in nums3:
            for j in nums4:
                if -(i+j) in dic.keys():
                    count += dic[-(i+j)]
        return count

这个解法会导致超时。下面的解法二完美通过。

解法二:

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
        """
        dic = dict()
        # 两两一组
        for i in nums1:
            for j in nums2:
                dic[i+j] = dic.get(i+j,0) + 1
        count = 0
        for i in nums3:
            for j in nums4:
                if -(i+j) in dic.keys():
                    count += dic[-(i+j)]
        return count

总结

对比发现,解法一和解法二的不同之处在于,解法二没有使用条件分支。联系到之前学的知识,对于分支语句,系统会根据一系列的策略去猜测这个会选择哪个分支并提前处理该分支,如果猜对了还好,猜错了就会浪费时间。所以算法中尽量少用分支。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值