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 <= nums[i] <= 109

0 <= sum(nums[i]) <= 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 分钟前
62. 不同路径
开发语言·数据结构·算法·leetcode·职场和发展·深度优先
小资同学13 分钟前
考研机试 -Kruskal算法
算法
big_rabbit050216 分钟前
[算法][力扣283]Move Zeros
算法·leetcode·职场和发展
小资同学18 分钟前
考研机试动态规划 线性DP
算法·动态规划
listhi52023 分钟前
两台三相逆变器并联功率分配控制MATLAB实现
算法
Evand J26 分钟前
【IMM】非线性目标跟踪算法与MATLAB实现:基于粒子滤波的交互式多模型,结合CV和CT双模型对三维空间中的机动目标进行高精度跟踪
算法·matlab·目标跟踪·pf·粒子滤波·imm·多模型
重生之后端学习27 分钟前
64. 最小路径和
数据结构·算法·leetcode·排序算法·深度优先·图论
We་ct1 小时前
LeetCode 212. 单词搜索 II:Trie+DFS 高效解法
开发语言·算法·leetcode·typescript·深度优先·图搜索算法·图搜索
样例过了就是过了1 小时前
LeetCode热题100 路径总和 III
数据结构·c++·算法·leetcode·链表
lxh01131 小时前
函数防抖题解
前端·javascript·算法