[LeetCode]523. Continuous Subarray Sum

https://leetcode.com/problems/continuous-subarray-sum/#/description

找到和为K的倍数的非负数组的最长连续子数组






1、处理k为0的情况;2、用HashMap保存sum对k取余数,如果前序有余数也为sum % k的位置,那么就存在连续子数组和为k的倍数

public class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        HashMap map = new HashMap();
        map.put(0, -1);
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            Integer prev = map.get(k == 0 ? sum : sum % k);
            if (prev != null) {
                if (i - prev > 1) {
                    return true;
                }
            } else {
                map.put(k == 0 ? sum : sum % k, i);
            }
        }
        return false;
    }
}


你可能感兴趣的:(LeetCode)