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

LeetCode 523: Continuous Subarray Sum

时间:2017-09-03 14:15:56      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:note   --   style   sum   rom   public   ret   log   bsp   

Note:

  1. The sum array need to be very clear that 0th is 0. So the sum[i] means from 0 to i - 1 sum.

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        if (nums.length < 2) {
            return false;
        }
        int[] sum = new int[nums.length + 1];
        
        for (int i = 0; i < nums.length; i++) {
            sum[i + 1] = sum[i] + nums[i];
        } 
        
        for (int i = 1; i < nums.length; i++) {
            for (int j = i - 1; j >= 0; j--) {
                 if (k == 0) {
                     if ((sum[i + 1] - sum[j]) == 0) {
                        return true;
                     }
                 } else if ((sum[i + 1] - sum[j]) % k == 0) {
                    return true;
                }
            }
        }
        return false;
    }
}

 

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

 

LeetCode 523: Continuous Subarray Sum

标签:note   --   style   sum   rom   public   ret   log   bsp   

原文地址:http://www.cnblogs.com/shuashuashua/p/7469386.html

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