Leetcode 523. Continuous Subarray Sum Prefix 坑

Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.

A good subarray is a subarray where:

its length is at least two, and

the sum of the elements of the subarray is a multiple of k.

Note that:

A subarray is a contiguous part of the array.

An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.

Example 1:

Input: nums = 23,2,4,6,7, k = 6

Output: true

Explanation: 2, 4 is a continuous subarray of size 2 whose elements sum up to 6.

Example 2:

Input: nums = 23,2,6,4,7, k = 6

Output: true

Explanation: 23, 2, 6, 4, 7 is an continuous subarray of size 5 whose elements sum up to 42.

42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.

Example 3:

Input: nums = 23,2,6,4,7, k = 13

Output: false

Constraints:

1 <= nums.length <= 105

0 <= numsi <= 109

0 <= sum(numsi) <= 231 - 1

1 <= k <= 231 - 1


It's easy to come up with prefix array, but the potential bug is that the its length is at least two. The following code is finished after several attempts:

python 复制代码
class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        l = len(nums)
        if (l <= 1):
            return False
        prefix_dic = {0:-1} # take care 0 is with any prefix
        cur_sum = 0
        
        for i in range(l):
            cur_sum = (cur_sum+nums[i]) % k
            # take care the following conditions
            if cur_sum in prefix_dic and (i-prefix_dic[cur_sum] >= 2):
                return True
            if cur_sum not in prefix_dic:
                prefix_dic[cur_sum] = i
        return False
相关推荐
木井巳10 分钟前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
怕浪猫1 小时前
从 Windows 换到 Mac 三个月,我真香了
算法·面试·架构
aichitang20242 小时前
前端小skill
前端·人工智能·算法·ai·前端框架
All for pursuit.3 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
木子算法3 小时前
测出来的值会抖:约束和目标带噪声时,「可行」和「更好」该怎么判
人工智能·算法·目标跟踪
圣保罗的大教堂3 小时前
leetcode 1477. 找两个和为目标值且不重叠的子数组 中等
leetcode
hanlin034 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode
金士曼4 小时前
从规则到涌现:算法认知的三个层次
算法
彧azz4 小时前
图的最短路径:Dijkstra与Floyd算法
数据结构·笔记·学习
智购科技自动售卖机厂家4 小时前
设备一到夏天就频繁跳闸,从启动电流追到压缩机电容~YH
数据结构·人工智能·python·eclipse