首页 > 其他分享 >【前缀和】LeetCode 523. 连续的子数组和

【前缀和】LeetCode 523. 连续的子数组和

时间:2023-04-16 10:56:57浏览次数:46  
标签:前缀 nums int 数组 523 new LeetCode

题目链接

523. 连续的子数组和

思路

参考宫水三叶大佬题解

一开始以为和 Leetcode 53 Maximum Subarray 思路差不多,都是求子数组的值。但是后来发现在53题中并没有求出每个子数组的和,只是在贪心的情况下求出了可能的最大和

代码

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        int n = nums.length;
        int[] sum = new int[n + 1];
        for(int i = 1; i <= n; i++){
            sum[i] = sum[i - 1] + nums[i - 1];
        }

        Set<Integer> set = new HashSet<>();
        for(int i = 2; i <= n; i++){
            set.add(sum[i - 2] % k);
            if(set.contains(sum[i] % k)){
                return true;
            }
        }

        return false;
    }
}

标签:前缀,nums,int,数组,523,new,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17322648.html

相关文章

  • LeetCode 115. 不同的子序列
    classSolution{public:longlongf[1010][1010];//f[i][j]表示s前i个字符得到t前j个字符的所有方案intnumDistinct(strings,stringt){f[0][0]=1;intn=s.size(),m=t.size();s=''+s;t=''+t;for(inti=1;i<=n;i+......
  • [leetcode每日一题]4.15
    1042. 不邻接植花提示中等181相关企业有 n 个花园,按从 1 到 n 标记。另有数组 paths ,其中 paths[i]=[xi,yi] 描述了花园 xi 到花园 yi 的双向路径。在每个花园中,你打算种下四种花之一。另外,所有花园 最多 有 3 条路径可以进入或离开.你需要为每个花园选择一......
  • leetcode:排序数组
    题目描述给你一个整数数组 nums,请你将该数组升序排列。示例1:输入:nums=[5,2,3,1]输出:[1,2,3,5]示例2:输入:nums=[5,1,1,2,0,0]输出:[0,0,1,1,2,5]题目地址:912.排序数组解题思路 这道题目直接告诉你了要排序,关键是选中什么样的排序算法?题目的限制条件是有两个,第......
  • LeetCode 538.把二叉搜索树转换成累加树
    1.题目:给出二叉搜索树的根节点,该树的节点值各不相同,请你将其转换为累加树(GreaterSumTree),使每个节点node 的新值等于原树中大于或等于 node.val 的值之和。提醒一下,二叉搜索树满足下列约束条件:节点的左子树仅包含键小于节点键的节点。节点的右子树仅包含键大于节点键的......
  • #yyds干货盘点# LeetCode程序员面试金典:K 个一组翻转链表
    题目:给你链表的头节点head,每 k 个节点一组进行翻转,请你返回修改后的链表。k是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。 示例1:输入:head=[1,......
  • #yyds干货盘点# LeetCode面试题:最小覆盖子串
    1.简述:给你一个字符串s、一个字符串t。返回s中涵盖t所有字符的最小子串。如果s中不存在涵盖t所有字符的子串,则返回空字符串""。 注意:对于t中重复字符,我们寻找的子字符串中该字符数量必须不少于t中该字符数量。如果s中存在这样的子串,我们保证它是唯一的答案。......
  • leetcode-1360-easy
    NumberofDaysBetweenTwoDatesWriteaprogramtocountthenumberofdaysbetweentwodates.Thetwodatesaregivenasstrings,theirformatisYYYY-MM-DDasshownintheexamples.Example1:Input:date1="2019-06-29",date2="201......
  • leetcode-844-easy
    BackspaceStringCompareGiventwostringssandt,returntrueiftheyareequalwhenbotharetypedintoemptytexteditors.'#'meansabackspacecharacter.Notethatafterbackspacinganemptytext,thetextwillcontinueempty.Example1:......
  • leetcode-830-easy
    PositionsofLargeGroupsInastringsoflowercaseletters,theselettersformconsecutivegroupsofthesamecharacter.Forexample,astringlikes="abbxxxxzyy"hasthegroups"a","bb","xxxx","z"......
  • leetcode-812-easy
    LargestTriangleAreaGivenanarrayofpointsontheX-Yplanepointswherepoints[i]=[xi,yi],returntheareaofthelargesttrianglethatcanbeformedbyanythreedifferentpoints.Answerswithin10-5oftheactualanswerwillbeaccepted.Exampl......