523. Continuous Subarray Sum
Solution
這題基本上也是透一樣的概念去找到符合的subArray但是edge case有點多
public boolean checkSubarraySum(int[] nums, int k) {
int newK = (k > 0) ? k : -k;
//continus 0 is all passed
for(int i = 1; i < nums.length; i++){
if(nums[i] == 0 && nums[i-1] == 0) return true;
}
//never possible
if( newK == 0 ){
return false;
}
//newK is 1 means any nums with length 2 is valid
if( newK == 1 ){
if(nums.length >= 2) return true;
else return false;
}
HashMap<Integer, Integer> map = new HashMap<>();
int sum = 0;
map.put(0, -1);
for(int i = 0; i < nums.length; i++){
sum += nums[i];
map.put(sum, i);
int checkSum = sum - newK;
while( checkSum >= 0){
if(map.get(checkSum) != null && i - map.get(checkSum) > 1) return true;
checkSum -= newK;
}
}
return false;
}
Last updated
Was this helpful?