[Lintcode]138. Subarray Sum

本文探讨了在整数数组中寻找子数组使元素之和为零的问题,提供了两种解决方案:一种使用Python字典,另一种使用map。通过比较相同前缀和的位置,找到满足条件的子数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

138. Subarray Sum

Description

Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.

Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

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

我的代码

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
        s_dic = {}
        s = 0
        for i,item in enumerate(nums):
            s += item
            if s == 0:
                return [0, i]
            if s in s_dic:
                return s_dic[s]+1, i
            else:
                s_dic[s] = i

别人的代码

class Solution:
    def subarraySum(self, nums):
        map, prefix_sum = {0: 0}, 0
        for i, n in enumerate(nums):
            prefix_sum += n
            if prefix_sum in map:
                return map[prefix_sum], i
            map[prefix_sum] = i + 1

思路

此题说的应该是连续的子列,所以可以比较他们从头到某处的和,如果两处和相同,则说明中间的子列相加效果为0。
我是用dictionary实现的。别人是用map实现的。原理相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值