机试打卡 -02 和为 K 的子数组(哈希表&前缀和)

 


枚举法,很容易想到↓

class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        
        # nums_len 数组长度
        nums_len=len(nums)
        answer_count=0

        n_sum=0

        # 滑动指针(right_pointer&left_pointer)
        for left_pointer in range(nums_len):
            for right_pointer in range(left_pointer,nums_len):
                n_sum+=nums[right_pointer]

                if n_sum==k:
                    answer_count+=1
                    continue

            n_sum=0

        return answer_count

但是又超时了……

为什么超时了?解释如下↓


 核心思想:前缀和+哈希表优化

 

class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        
        # nums_len 数组长度
        nums_len=len(nums)

        answer_count=0

        # 建立哈希表,以前缀和为键,出现的次数为值
        Hash=dict()

        # 必须将Hash[0]=1初始化,否则无法判断start=0的子数组是否满足条件
        Hash[0]=1

        pre=0

        for i in range(nums_len):
            pre+=nums[i]

            # 由于i>j,必须最后更新Hash表
            if pre-k in Hash:
                answer_count+=Hash[pre-k]
            else:
                pass

            #将pre[i]的值加入Hash表
            Hash[pre]=Hash[pre]+1 if pre in Hash else 1

        return answer_count


哈希表(hash table),也叫作散列表,这种数据结构提供了键(key)和值(value)的映射关系。只要给出一个key,就可以高效查找到它所匹配的value,时间复杂度接近于O(1)。
哈希函数就是将key和value值对应起来的函数。在不同语言中,哈希函数的实现方式是不一样的,在python语言中,哈希表对应的集合叫做字典(dict)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值