lintcode练习-138. 子数组之和

描述

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

There is at least one subarray that it's sum equals to zero.

您在真实的面试中是否遇到过这个题?  是

样例

给出 [-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].

实现代码:

直接两个循环比较,比较耗时

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
        point_list = []
        n = len(nums)
        for i in range(n):
            count = 0
            for j in range(i, n):
                count += nums[j]
                if count == 0:
                    return [i, j]

利用哈希表来实现:

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):
        if not nums:
            return -1
        #初始化,
        seen = {0: 0}
        prefixSum = 0
        for i, num in enumerate(nums):
            prefixSum += num
            # 对sum进行判断,如果在哈希表中,则说明sum为0,或者相邻元素互为相反数
            if prefixSum in seen:
                return (seen[prefixSum], i)
            seen[prefixSum] = i + 1

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81226639