Subarray Sum Closet

Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

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

这题求和最接近0的子数组,属于Subarray Sum的follow up.思路也很近似,每次求的是当前位置及之前的数组的一个和.但是这题并不是等于0,不会有一样的和出现,所以使用hashmap没什么可能.

在这种情况下,维护一个<sum,index>的pair的一个数组,将数组按sum值排个序.在排序后数组中找相邻位置的差值的绝对值最小的index. 小的是subarray开始的前面的一个index, 大的就是结尾的index.复杂度分析:

1.求<sum,index>的pair数组时间复杂度O(n).

2.排序O(nlogn)

3.相邻的挨个比较O(n)

总体时间复杂度为O(n),空间复杂度为O(n).

注意<res,index>这种pair的技术在two pointer等题中经常用,设置key值比较的技术一定要会.代码如下:

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 subarraySumClosest(self, nums):
        #two pointer
        res = []
        sum = 0
        for i in xrange(len(nums)):
            sum += nums[i]
            res.append((sum,i))
        res.sort(key = lambda x: x[0])

        left = -1
        right = 0
        diff = abs(res[0][0])
        for i in xrange(1,len(nums)-1):
            if abs(res[i][0] - res[i-1][0]) < diff:
                left = min(res[i-1][1], res[i][1])
                right = max(res[i-1][1], res[i][1])
                diff = abs(res[i][0] - res[i-1][0])
        
        return [left+1, right]    
            
原文地址:https://www.cnblogs.com/sherylwang/p/5572747.html