标签:put ++ int sum ++i boolean tco which return
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
标签:put ++ int sum ++i boolean tco which return
原文地址:https://www.cnblogs.com/exhausttolive/p/10618391.html