leetcode 523. Continuous Subarray Sum
Posted exhausttolive
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 523. Continuous Subarray Sum相关的知识,希望对你有一定的参考价值。
prefix sum
k = 0 is a corner case, in which case just save <prefix_sum, index>, not <prefix_sum % k, index>
And every time, record the leftmost index of a key.(greedy)
class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
if (nums.length < 2) return false;
Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
int sum = 0;
counter.put(0, -1);
for (int i = 0; i < nums.length; ++i) {
sum += nums[i];
int mod = k != 0? sum % k: sum;
if (counter.get(mod) != null) {
if (i - counter.get(mod) > 1) return true;
}
else {
counter.put(mod, i);
}
}
return false;
}
}
以上是关于leetcode 523. Continuous Subarray Sum的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 523. Continuous Subarray Sum
LeetCode 523: Continuous Subarray Sum
Leetcode 523. Continuous Subarray Sum