1. 程式人生 > >LeetCode 523: Continuous Subarray Sum

LeetCode 523: Continuous Subarray Sum

div nbsp span -1 logs tin dex spa pre

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