523. Continuous Subarray Sum

题目

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.

分析

给定一个非负整数数组nums和一个目标整数k,判断nums中是否存在一个连续子数组使得子数组的和是k的倍数。
开始想到的是用和数组,然后设定间距从2到Nums.length,依次检测,可以过但是比较慢。
看了discuss中用了一种比较好的利用余数的思想:若sum1 % k = x且sum2 % k = x,则sum2 - sum1一定是k的倍数,所以用一个map来保存累加后和的余数以及对应的index
写代码时还有一些细节需要注意,比如k如果为0,sum和余数用一个变量,如果map已经有值了就不再覆盖(保留最长的情况)

代码

public boolean checkSubarraySum(int[] nums, int k) {
    if(nums.length <= 1) return false;
    
    Map map = new HashMap();
    map.put(0, -1);  //细节1: 保留0,方便从0开始
    
    int sum = 0;
    for(int i = 0; i < nums.length; ++i){
        sum += nums[i];
        if(k != 0) sum %= k;   //细节2: 考虑k == 0,且和和取余结果通用一个变量
        Integer prev = map.get(sum);
        if(prev != null){
            if(i - prev > 1){
                return true;
            }
        }
        else   //else很关键,如果有一样的又没有到2个间距,则保留前面的结果
            map.put(sum, i);
    }
    
    return false;
}

你可能感兴趣的:(523. Continuous Subarray Sum)