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:

Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4 
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.

Example 2:

Input: nums = [-2, -1, 2, 1], k = 1
Output: 2 
Explanation: The subarray [-1, 2] sums to 1 and is the longest.

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

解题思路:

需要注意的是这里的subarray是连续的。

因为这里要求和,我们可以从左向右求累加和sum:

  1.若sum = k,则ret = i+1.

  2.若sum != k,则检查之前又没有出现过 sum - k。(这种情况下是起点从中间开始)

    若出现过:则长度为:i- m[sum-k]

 因为我们要查询收否有累加值存在,我们可以用hashmap来进行快速存取。

 所以我们也要把sum放到hashmap中,因为数组中会有负数出现,可能会出现相等的sum值,因为我们要求的是最长的子数组,所以只需要记录第一个出现的位置。

代码:

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

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9194360.html
今日推荐