码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 523. Continuous Subarray Sum

时间:2019-03-28 23:14:28      阅读:186      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!