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
相关推荐
张二娃同学7 分钟前
03_变量常量与输入输出_printf与scanf详解
算法
江南十四行1 小时前
并发编程(一)
java·jvm·算法
z200509301 小时前
今日算法(依旧二叉树)
算法·leetcode·职场和发展
Zxc_1 小时前
《遗传算法:从自然选择到Rastrigin函数优化,手写一个完整的进化求解器》
算法
阿Y加油吧2 小时前
两道经典动态规划题:乘积最大子数组 & 分割等和子集 复盘笔记
笔记·算法·动态规划
三品吉他手会点灯2 小时前
C语言学习笔记 - 33.数据类型 - printf函数的详细用法
c语言·开发语言·笔记·学习·算法
NashSKY2 小时前
PnP 问题:数学描述与 DLT 算法推导
算法·矩阵分解·多视图几何·射影几何
csdn_aspnet3 小时前
C++ Lomuto分区算法(Lomuto Partition Algorithm)
开发语言·c++·算法
ZPC82103 小时前
Open3D 与yolo-3d 那个更适合生成物体3d 包围盒
人工智能·算法·计算机视觉·机器人
行走的陀螺仪3 小时前
JavaScript 算法详解:10大经典算法,通俗易懂,从入门到精通
开发语言·javascript·算法