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
相关推荐
芒克芒克16 小时前
数组去重进阶:一次遍历实现最多保留指定个数重复元素(O(n)时间+O(1)空间)
数据结构·算法
星火开发设计16 小时前
二维数组:矩阵存储与多维数组的内存布局
开发语言·c++·人工智能·算法·矩阵·函数·知识
Fcy64817 小时前
⽤哈希表封装unordered_map和unordered_set(C++模拟实现)
数据结构·c++·散列表
丨康有为丨17 小时前
算法时间复杂度和空间复杂度
算法
HarmonLTS17 小时前
Python人工智能深度开发:技术体系、核心实践与工程化落地
开发语言·人工智能·python·算法
a程序小傲17 小时前
京东Java面试被问:RPC调用的熔断降级和自适应限流
java·开发语言·算法·面试·职场和发展·rpc·边缘计算
一分之二~17 小时前
二叉树--层序遍历(迭代和递归)
数据结构·c++·算法·leetcode
zl_vslam17 小时前
SLAM中的非线性优-3D图优化之绝对位姿SE3约束右扰动(十七)
人工智能·算法·计算机视觉·3d
Cestb0n17 小时前
某果app 加密校验算法逆向分析
python·算法·逆向安全
机器学习之心18 小时前
MATLAB基于近红外光谱检测的菠萝含水率预测(多种预处理+PLS)
人工智能·算法·matlab·近红外光谱检测