[LeetCode 325] Maximum Size Subarray Sum Equals k

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.

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?

Diffculty
Medium

Similar Problems
[LeetCode 209] Minimum Size Subarray Sum Medium [LeetCode 303] Range Sum Query - Immutable Easy

Analysis

然而当我上网看大神们的解法时,才发现我图样图森破,根本不需要我写的那么复杂,我们不需要另外创建一个累积和的数组,而是直接用一个变量sum边累加边处理,而且我们哈希表也完全不用建立和一维数组的映射,只要保存第一个出现该累积和的位置,后面再出现直接跳过,这样算下来就是最长的子数组,想出这解法的人你咋不上天呢,参见代码如下:

http://www.cnblogs.com/grandyang/p/5336668.html

results matching ""

    No results matching ""