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
相关推荐
小欣加油1 天前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
lqqjuly1 天前
前沿算法深度解析(二)
人工智能·算法·机器学习
徐小夕1 天前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
akunkuntaimei1 天前
2026年高考数学各省真题及答案(完整版)
算法·高考
Hello:CodeWorld1 天前
C 风格变参 vs C++ 变参模板:核心区别与选型指南
c语言·c++·算法
8Qi81 天前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
youngerwang1 天前
【从搬运工到协处理器:网卡芯片架构、算法、验证与边缘演进深度剖析】
网络·算法·架构·芯片
想要成为糕糕手1 天前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
KaMeidebaby1 天前
卡梅德生物技术快报|纯化重组蛋白实操详解
人工智能·python·tcp/ip·算法·机器学习
手写码匠1 天前
从零实现 Prompt 工程引擎:结构化提示、自动优化与多轮自省体系
人工智能·深度学习·算法·aigc