[leetcode] 325. Maximum Size Subarray Sum Equals k 解题报告

题目链接:https://leetcode.com/problems/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?


思路:时间复杂度为O(n^2)的思路比较好想,O(n)的想了好久没想到怎么做,后来才知道可以用hash表来保存以往的和,然后每次去查是否当前和减去目标值已经存在, 是的话说明我们找到了一个序列,然后更新最大长度大小.另外一个需要注意的是初始值.当什么都不拿时位置设为-1.

代码如下:

class Solution {
public:
    int maxSubArrayLen(vector<int>& nums, int k) {
        if(nums.size() ==0) return 0;
        unordered_map<int, int> hash;
        hash[0] = -1;
        int sum =0, result = 0;
        for(int i =0; i< nums.size(); i++)
        {
            sum += nums[i];
            if(hash.find(sum)== hash.end())
                hash[sum] = i;
            if(hash.find(sum-k) != hash.end())
                result = max(result, i-hash[sum-k]);
        }
        return result;
    }
};
参考:https://leetcode.com/discuss/86319/sharing-my-100ms-simple-c-solution

你可能感兴趣的:(LeetCode,hash,Facebook)