lintcode 138. Subarray Sum

难度:容易

1. Description

138. Subarray Sum

2. Solution

  • python
    暴力方法,时间复杂度O(n^2)
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
        for i in range(len(nums)):
            m_sum = 0
            for j in range(i,len(nums)):
                m_sum += nums[j]
                if(m_sum==0):
                    return [i,j]

用前缀和,时间复杂度O(n)
前缀和prefix_sum[i] = nums[0]+nums[1]+...nums[i],即数组前i项和。
利用nums[i+1]+nums[i+1]+...+nums[j] = prefix_sum[j]-prefix_sum[i]
prefix_sum[j]=prefix_sum[i]时,i+1到j的子串和为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
        prefix_hash = {0:-1}
        prefix_sum = 0
        for i in range(len(nums)):
            prefix_sum += nums[i]
            if prefix_sum in prefix_hash.keys():
                return prefix_hash[prefix_sum]+1,i
            prefix_hash[prefix_sum] = i
        return -1,-1

3. Reference

  1. https://www.lintcode.com/problem/subarray-sum/description
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 2,226评论 0 3
  • 原题 给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置。 给出[-3, ...
    Jason_Yuan阅读 398评论 0 1
  • 解法一:暴力搜索,遍历两个坐标的可能性,O(n^2); 解法二:类似于暴力搜索,但是!!记录的是累加和,当两个位置...
    刘小小gogo阅读 225评论 0 0
  • 文/秦溯之 夏日寻荷叠翠乡,芳菲漫处见幽篁。 蝉鸣翠柳丝绦上,蛙唱清池碧叶旁。 菡萏初开光日月,浮香暗动起荷塘。 ...
    秦溯之阅读 549评论 4 4