题目:
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?
思路:
1、暴力法:首先计算出数组的累积和(这样就可以在O(1)的时间内求出任意区间内的数字和),然后两遍循环穷举各种区间的情况。时间复杂度是O(n^2),空间复杂度是O(n)。竟然能通过数据测试,但是显然不符合题目要求。
2、哈希表法:用哈希表可以巧妙降低时间复杂度,思路优点像two sum这一问题。我们定义一个哈希表,使得hash[sum] == i表示[0,i]区间内的数字和是sum。这样在遍历数组中的数字的时候,假设累积和是sum,一旦发现(sum - k)已经在哈希表中出现,则说明区间[hash[sum - k], i]的和就是k,此时就可以更新返回值的大小。当然在遍历的同时也需要检查hash[sum]是否存在,如果不存在,就需要添加(但是如果已经存在,则不需要更新,请思考为什么^_^)。该算法的时间复杂度和空间复杂度都是O(n)。
代码:
1、暴力法:
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
int size = nums.size(), sum = 0, ret = 0;
if (size == 0) {
return 0;
}
vector<int> sums(size, 0);
sums[0] = nums[0];
for (int i = 1; i < size; ++i) {
sums[i] = sums[i - 1] + nums[i];
}
for (int end = size - 1; end >= 0; --end) {
for (int start = 0; start <= end; ++start) {
sum = (start == 0) ? sums[end] : sums[end] - sums[start - 1];
if (sum == k) {
ret = max(ret, end - start + 1);
}
}
}
return ret;
}
};
2、哈希表法:
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
if (nums.size() == 0) {
return 0;
}
unordered_map<int, int> hash;
int sum = 0, ret = 0;
hash[0] = 0;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
if (hash.count(sum - k)) {
ret = max(ret, i - hash[sum - k] + 1);
}
if (!hash.count(sum)) {
hash[sum] = i + 1;
}
}
return ret;
}
};