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.

Note:
The length of the array won't exceed 10,000.
You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

答案
定义subsum[i][j] = sum of subarray between index i and j
base case: subsum[i][j] = nums[i], for all i = j
recursive case: subsum[i][j] = subsum[i][j - 1] + nums[j], for all i < j

如果存在subsum[i][j], 使得其值可以整除k,而且j - i > 0,则有continuous sub array that adds to multiple of k.
另外要注意处理以下k = 0的情况,避免除0异常

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {       
        int[][] subsum = new int[nums.length][nums.length];
        for(int i = nums.length; i >= 0; i--) {
            for(int j = i; j < nums.length; j++) {
                if(i == j) {
                    subsum[i][j] = nums[i];
                }
                else {
                    subsum[i][j] = subsum[i][j - 1] + nums[j];
                }
                if(j - i > 0 && ((k == 0 && subsum[i][j] == 0) || (k != 0 && subsum[i][j] % k == 0)) )
                    return true;
            }
        }
        return false;
    }
}

以上解法因为用的空间是O(n^2)而没有被Leetcode accept,稍微改一下即可通过Leetcode OJ:

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        int subsumij, subsumijminusone = 0;
        for(int i = nums.length; i >= 0; i--) {
            for(int j = i; j < nums.length; j++) {
                if(i == j) {
                    subsumij = nums[i];
                }
                else {
                    subsumij = subsumijminusone + nums[j];
                }
                if(j - i > 0 && ((k == 0 && subsumij == 0) || (k != 0 && subsumij % k == 0)) )
                    return true;
                subsumijminusone = subsumij;
            }
        }
        return false;
    }
}

另一种解法
出处:https://leetcode.com/problems/continuous-subarray-sum/discuss/99499

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        Map map = new HashMap(){{put(0,-1);}};;
        int currsum = 0;
        for(int i = 0; i < nums.length; i++) {
            currsum += nums[i];
            if(k != 0) currsum %= k;
            Integer last = map.get(currsum);
            if(last != null)  {
                if(i - last > 1)
                    return true;
            }
            else map.put(currsum, i);
        }
        return false;
    }
}

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