[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.

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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值