前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[LeetCode] 523. Continuous Subarray Sum

[LeetCode] 523. Continuous Subarray Sum

作者头像
用户1148830
发布2018-01-04 09:54:25
7910
发布2018-01-04 09:54:25
举报

【原题】 Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.

Example 1:

Input: [23, 2, 4, 6, 7], k=6 Output: True Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Example 2:

Input: [23, 2, 6, 4, 7], k=6 Output: True Explanation: Because [23,2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

【解释】 给定一个数组和一个target,要求返回数组中是否存在连续子数组的和是k的倍数,要求连续子数组的元素个数大于2 【思路】

思路一、 直接从每一个元素开始,依次和其后的元素分别相加,如果为k的倍数返回true即可。O(n^2)的解法,这里略过。

思路二、 o(n^2)的方法有点low,想用求最大子数组和的滑动窗口的思想来做,但没有解出来。于是就看了solution。 需要使用一个定理:

如果x和y除以z同余,那么x-y一定可以整除z

代码语言:javascript
复制
public boolean checkSubarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(0, -1);//为了处理nums=[0,0] k=-1这样的情况
        int sum = 0;
        for (int i=0;i<nums.length;i++) {
            sum += nums[i];
            if (k != 0) sum %= k; 
            Integer prev = map.get(sum);
            if (prev != null) {
                if (i - prev > 1) return true;//若找到相同的余数,并且元素不少于两个,利用上面的定理,则返回true
            }
            else map.put(sum, i);//否则将余数和index保存至map
        }
        return false;
    }

这种题目之前没有做过确实很难想到这样的解法,具有很强的技巧性。

参考: https://discuss.leetcode.com/topic/80793/java-o-n-time-o-k-space

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年07月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档