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
相关推荐
橘和柠3 小时前
知识图谱实战(一):数据采集与实体关系抽取(完整代码)
算法
Mem0rin3 小时前
前缀和:中心下标与数组乘积
数据结构·算法
Lazionr3 小时前
list容器详解——双向链表的封装与使用
数据结构·c++·链表·list
windliang3 小时前
Claude Code 源码分析(八):Memory 如何被写入、整理与按需召回
前端·算法·面试
漂流瓶jz3 小时前
UVA-12174 Shuffle的播放记录 题解答案代码 算法竞赛入门经典第二版
数据结构·c++·算法·图论·滑动窗口·算法竞赛入门经典·uva
Forever Nore3 小时前
LeetCode 6 Z 字形变换 - 按行模拟
算法·leetcode
lingran__3 小时前
C++ 高阶数据结构:红黑树万字详解|完整原理推导 + 插入实现 + 完整性校验【STL 底层】
数据结构·c++·面试·红黑树·二叉搜索树·平衡二叉树·stl底层
fkyyly4 小时前
hermes解读
算法·code_agent
过期的秋刀鱼!4 小时前
使用都热编码的分类特征
人工智能·算法·决策树·机器学习·分类·数据挖掘
wabs6664 小时前
关于哈希表【力扣383.赎金信的思考】
算法·leetcode·散列表