138. 子数组之和

138. 子数组之和

中文 English

给定一个整数数组,找到和为 00 的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置

样例

样例 1:

输入: [-3, 1, 2, -3, 4]
输出: [0,2] 或 [1,3]	
样例解释: 返回任意一段和为0的区间即可。

样例 2:

输入: [-3, 1, -4, 2, -3, 4]
输出: [1,5]

注意事项

至少有一个子数组的和为 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
        #前缀和写法,只要取得后面的前缀和和前面的前缀和相等的情况即可
        
        perfixsum_hash = {0: -1}
        prefix_sum = 0
        
        for i, num in enumerate(nums):
            prefix_sum += num
            if prefix_sum in perfixsum_hash:
                #减去的是后面减去前面的前缀和,返回的应该是prefixsum_hash[prefix_sum] + 1, i
                return perfixsum_hash[prefix_sum] + 1, i
            perfixsum_hash[prefix_sum] = i 

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/13379962.html