Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Continuous Subarray Sum

$
0
0

题目描述:

LeetCode 523. Continuous Subarray Sum

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.

Note:

  1. The length of the array won't exceed 10,000.
  2. You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

题目大意:

求数组nums中是否存在k的整数倍,并且长度至少为2的连续子段和。

注意:

  1. 数组长度不超过10,000。
  2. 可以假设所有数字的和范围在32位带符号整数之内。

解题思路:

遍历数组nums,求前i项和total;对k取模,记模值为m

利用dmap[m]记录模为m的前i项和的最小下标,初始令dmap[0] = -1

若dmap[m] + 1 < i,则返回True

Python代码:

class Solution(object):
    def checkSubarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dmap = {0 : -1}
        total = 0
        for i, n in enumerate(nums):
            total += n
            m = total % k if k else total
            if m not in dmap: dmap[m] = i
            elif dmap[m] + 1 < i: return True
        return False

 


Viewing all articles
Browse latest Browse all 559

Trending Articles