原题链接在这里:https://leetcode.com/problems/continuous-subarray-sum/description/
题目:
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.
题解:
需要求有没有一段长度大于等于2的subarray的和是k的倍数.
保存之前每个点sum%k的值, 若是又出现了相同的值, 那么这一段subarray的和就是k的倍数.
然后看看这段长度是否大于等于2.
初始化HashMap<Integer, Integer> hm来记录到index i 时的sum%k 和 i的对应关系.
先赋值(0,-1). 原因是sum有包括nums[0]的情况.
这里通过初始index -1 和 i - hm.get(sum%k) > 1来确保.
计算当前值的sum, 若k不是0, sum = sum%k. 看hm中是否已经有过这个余数, 若有看index差是否大于1, 没有就加进hm中.
答案有大于1的return true说明减掉之前的那段正好把余数减光. 若一直没有return false.
Time Complexity: O(nums.length).
Space: O(nums.length).
AC Java:
1 class Solution { 2 public boolean checkSubarraySum(int[] nums, int k) { 3 HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); 4 hm.put(0,-1); 5 6 int sum = 0; 7 for(int i = 0; i<nums.length; i++){ 8 sum += nums[i]; 9 if(k != 0){ 10 sum = sum%k; 11 } 12 13 if(hm.containsKey(sum)){ 14 if(i-hm.get(sum)>1){ 15 return true; 16 } 17 }else{ 18 hm.put(sum, i); 19 } 20 } 21 return false; 22 } 23 }