Monday, February 1, 2016

325. Maximum Size Subarray Sum Equals k ----M ~~~~·

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?

A:
先求accumulate sum,并放到HashMap里,记住,相同的sum,只存最前面的那个。
然后 查看 已有的值里面,是否含有 total - k  。  (Note: total == 0 一开始就放进去)

class Solution {
public:
    int maxSubArrayLen(vector<int>& nums, int k) {
        int n = nums.size();
        unordered_map<int, int> M; // only save the first appearance
        M[0] = -1;
        int total = 0;
        int maxLen = 0;
        for(int i =0; i<n; i++){
            total += nums[i];
            if(M.find(total - k) != M.end()){
                maxLen = max(maxLen, i- M[total-k]);
            }
            if(M.find(total) == M.end()){
                M[total] = i;
            }
        }
        return maxLen;
    }
};

*****************上面是O(n^2).  如果要O(n)。 少了一个量级************这时候,就需要考虑Hashing *********(如果减少的是Log(n)级别,就可以考虑binary search, tree 等************


Mistakes:
1: 



No comments:

Post a Comment