LeetCode523 Continuous Subarray Sum
Check if contains a subarray that sum up equals to times of k
and pay attention: all elements in given array are non-negative.
this problem is pretty easy, still, I stucked on conner case which k==0 for a really long time.
My codes are as follows. the time complexity will be O(n^2).
class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
if (nums == null || nums.length < 2) {
return false;
}
int[] cul = new int[nums.length+1];
cul[0] = 0;
for (int i = 1; i<=nums.length; i++) {
cul[i] = nums[i-1] + cul[i-1];
System.out.println(cul[i]);
}
for (int i = 0; i<=nums.length-2; i++) {
for (int j = i+2; j <= nums.length; j++) {
if (k != 0 && (cul[j] - cul[i]) % k == 0) {
return true;
} else if (k == 0 && cul[j] - cul[i] == 0) {
return true;
}
}
}
return false;
}
}
and this problem can also be solved in hashmap.
and if you take a look at the code, we know that we have seem this pattern for many times: contrcuct the hashmap while using it to check, it’s like ji two pointers, but every information of j pointers has already stored in hashmap, we don’t have to iterate every thing from 0 to i-1 to identify j, just check it using hashmap.
and this hashmap method can shorten time complexity in a significant way.
public class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
int sum = 0;
HashMap <Integer, Integer> map = new HashMap <>(); //hashmap uses culmulative sum % k as the key, and the index as value. this is very genius, because if we have sum[j]%k == sum[i]%k, that means sum[j]-sum[i] is actuallt the times of K! and nums[i+1,j] must be the subarray we are looking for! and the only thing we need to check is whether j-i>=2 or not, if it is, then that the subarray we are looking for
map.put(0, -1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (k != 0)
sum = sum % k;
if (map.containsKey(sum)) {
if (i - map.get(sum) > 1) //if the distance between those things are larger or equals to 2
return true; //then we found a solution
} else
map.put(sum, i);
}
return false;
}
}

浙公网安备 33010602011771号