LeetCode 523: Continuous Subarray Sum
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 523: Continuous Subarray Sum相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 523. Continuous Subarray Sum
LeetCode 523: Continuous Subarray Sum
Leetcode 523. Continuous Subarray Sum