欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

lintcode:子数组之和

程序员文章站 2022-03-05 13:45:42
...

lintcode:子数组之和

class Solution:
    """
    @param nums: A list of integers
    @return: A list of integers includes the index of the first number 
             and the index of the last number
    """
    def subarraySum(self, nums):
        # write your code here

        # 1314ms
        n = len(nums)
        for st in range(n):
            a = 0
            for ed in range(st, n):
                a += nums[ed]
                if a == 0:
                    return [st, ed]

        # hashmap 1183ms
        n, a, d = len(nums), 0, {0:-1}
        for i in range(n):
            a += nums[i]
            if a in d:
                return [d.get(a) + 1, i]
            d[a] = i