Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

求一个最短的数组,使其和大于等于给定的s.

暴力解法是枚举左端,右端,判断是否和大于s。求和可以先用prefix sum使每次求和运算复杂度降低为O(1)。所以总体的时间复杂度为O(n^2)。可以想想如何优化。考虑下二维for循环如何优化,如果i表示左端,j表示右端,则如果sum[i,j] >s,则对于这个i,j没有必要再增大。可以去处理下一个i。如果sum[i,j] < s, 则j减小和肯定小于s,没必要减小。

总结,sum[i,j] <s, j ++

        sum[i,j] =s, i++。

所以i,j都朝着一个方向走属于前向形指针。

时间复杂度为O(n)。代码如下:

class Solution:
     # @param nums: a list of integers
     # @param s: an integer
     # @return: an integer representing the minimum size of subarray
    def minimumSize(self, nums, s):
        if not nums:
            return -1
        pSum =[0]
        res = sys.maxint
        for i in xrange(len(nums)):
            pSum.append(pSum[-1] + nums[i])
        i = 0
        j = 1
        while j < len(nums) + 1:
            if pSum[j] - pSum[i] >= s:
                res = min(res, j - i)
                i += 1
            else:
                j += 1
        return res if res != sys.maxint else -1

 

posted on 2016-07-16 22:16  Sheryl Wang  阅读(177)  评论(0编辑  收藏  举报

导航