[LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于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?

给一个数组nums和一个目标值k,找出子数组和是k的最大长度,如果没有返回0.  要求O(n)时间复杂度。

解法1:双指针,双层循环计算所有的组合,判断是否和为k,如果是,更新max_len。时间复杂度高,TLE

解法:循环数组,用一个变量 cur_sum 记录到目前为止所有数组的和,如果等于k则更新max_len,在用一个 map 记录累加和的index,技巧:因为是求最长数组,所以一个和只记录第一次的index,以后出现的位置靠后,就不记录了。如果cur_sum在hashmap 中,表示当前位置去掉hashmap中记录的cur_sum - k的 index 的和等于k,  用两个index的差更新max_len。

Java:

public int maxSubArrayLen(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int max = 0;
int sum=0;
for(int i=0; i<nums.length; i++){
sum += nums[i]; if(sum==k){
max = Math.max(max, i+1);
} int diff = sum-k; if(map.containsKey(diff)){
max = Math.max(max, i-map.get(diff));
} if(!map.containsKey(sum)){
map.put(sum, i);
}
} return max;
}  

Python: Time:  O(n), Space: O(n)

class Solution(object):
def maxSubArrayLen(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sums = {}
cur_sum, max_len = 0, 0
for i in xrange(len(nums)):
cur_sum += nums[i]
if cur_sum == k:
max_len = i + 1
elif cur_sum - k in sums:
max_len = max(max_len, i - sums[cur_sum - k])
if cur_sum not in sums:
sums[cur_sum] = i # Only keep the smallest index.
return max_len 

Python: wo

class Solution():
def maxSubarry(self, nums, k):
m = {0: -1}
sm = 0
for i in range(len(nums)):
sm += nums[i]
if sm not in m:
m[sm] = i
if sm - k in m:
max_len = max(max_len, i - m[sm-k]) return max_len  

C++:

class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
int sum = 0, res = 0;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
if (sum == k) res = i + 1;
else if (m.count(sum - k)) res = max(res, i - m[sum - k]);
if (!m.count(sum)) m[sum] = i;
}
return res;
}
};

  

类似题目:

[LeetCode] 53. Maximum Subarray 最大子数组

[LeetCode] 209. Minimum Size Subarray Sum 最短子数组之和

[LeetCode] 560. Subarray Sum Equals K 子数组和为K

Range Sum Query - Immutable

All LeetCode Questions List 题目汇总

上一篇:1Z0-053 争议题目解析706


下一篇:VR全景加盟-了解VR就来全景智慧城市