[LeetCode]Continuous Subarray Sum

523. Continuous Subarray Sum

题意:计算是否存在和为k的倍数连续子数组。

思路:不是很懂,大致上是说,如果第一次遇见不存在的模的结果时,则保存下来,但是如果遇到多个相同的求模的结果,说明它们之间的和必然是k的倍数。

class Solution(object):
    def checkSubarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        if len(nums) < 2:
            return False
        if k == 0:
            return sum(nums) == 0 and len(nums) >= 2
        setS = {0:-1}
        total = 0
        for i, num in enumerate(nums):
            total += num
            if total%k not in setS:
                setS[total%k] = i
            elif setS[total%k] != i-1:
                return True
        return False
posted @ 2017-08-29 19:30  banananana  阅读(127)  评论(0)    收藏  举报