Continuous Subarray Sum

来源:互联网 发布:python矩阵求和 编辑:程序博客网 时间:2024/06/03 18:20

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.

Example 1:

Input: [23, 2, 4, 6, 7],  k=6Output: TrueExplanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Example 2:

Input: [23, 2, 6, 4, 7],  k=6Output: TrueExplanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

java

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

python

class Solution(object):    def checkSubarraySum(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """        if nums == None or len(nums) == 0 or len(nums) == 1:            return False        mapping, summary = {}, 0        mapping[0] = 0        for i in range(len(nums)):            if k != 0:                summary = (summary + nums[i]) % k            else:                summary = summary + nums[i]            if summary in mapping:                index = mapping[summary]                if (i - index >= 1):                    return True                else:                    continue            else:                mapping[summary] = i + 1        return False        


原创粉丝点击