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

LintCode 138. Subarray Sum

程序员文章站 2022-03-24 17:38:20
...

题目

LintCode 138. Subarray Sum

思路

trick。如果0i的和等于0j的和,那么ij的和为0。

代码

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
        tmp_dict = {}
        tmp_dict[0] = -1
        sum = 0
        for i, v in enumerate(nums):
            sum += v
            if sum in tmp_dict:
                res_list = []
                res_list.append(tmp_dict[sum] + 1)
                res_list.append(i)
                return res_list
            tmp_dict[sum] = i