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.
題目大意:給定一個數組,一個k,找出數組中是否存在長度大於等於2的連續的子數組,使連續子數組的和是k的倍數。
思路:建立一個runningSum變量,記錄遍歷過程中連續子數組和模k的結果,並將結果存儲到Hashmap中,如果發現當前下標爲j的runningSum,在前面已經出現,則代表在之前出現的位置i到當前位置j,(i,j]處,存在連續子數組和可以整除k。
代碼
package DP; import java.util.HashMap; import java.util.Map; /** * @author OovEver * 2018/1/3 10:34 */ public class LeetCode523 { public static boolean checkSubarraySum(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int runningSum = 0; for(int i=0;i<nums.length;i++) { runningSum += nums[i]; if (k != 0) { runningSum %= k; } Integer prev = map.get(runningSum); if (prev != null) { // 連續子數組的長度需要大於2 if (i - prev > 1) { return true; } } else { map.put(runningSum, i); } } return false; } }