码迷,mamicode.com
首页 > 其他好文 > 详细

325. Maximum Size Subarray Sum Equals k

时间:2017-05-12 23:54:03      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:选项   long   ash   max   sel   bit   guarantee   ant   class   

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn‘t one, return 0 instead.

Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.

Example 1:

Given nums = [1, -1, 5, -2, 3], k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)

Example 2:

Given nums = [-2, -1, 2, 1], k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)

Follow Up:
Can you do it in O(n) time?

 

这一题由于数列不是sorted,所以不能用头尾指针的方法。使用一个sum_array, [1, -1, 5, -2, 3] 的sum_array就是【1,0,5,3,6】。如果sum_array中的两个数相差k, 那么这个subarray也是一个候选项。这里由于为了快速查找,使用了hash table。

class Solution(object):
    def maxSubArrayLen(self, nums, k):

        result, acc = 0, 0
        dic = {}

        for i in xrange(len(nums)):
            acc += nums[i]
            if acc == k:
                result = max(result, i + 1)
            if acc not in dic:
                dic[acc] = i
            if acc - k in dic:
                result = max(result, i - dic[acc-k])

        return result

 

325. Maximum Size Subarray Sum Equals k

标签:选项   long   ash   max   sel   bit   guarantee   ant   class   

原文地址:http://www.cnblogs.com/lettuan/p/6847575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!