• 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;
        }
    };
  • 相关阅读:
    PHP数组
    java中线程池的几种实现方式
    JAVA是是如何处理字符的。
    byte范围及8种常见数据类型
    对Spring 及SpringMVC的理解
    Nginx+Tomcat搭建负载均衡
    nginx + tomcat配置负载均衡
    Java并发编程:Lock
    Java内部类详解
    奇怪的Java题:为什么1000 == 1000返回为False,而100 == 100会返回为True?
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9194360.html
Copyright © 2020-2023  润新知