[LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组

2021年09月15日 阅读数:1
这篇文章主要向大家介绍[LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于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.html

Example 1:java

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)python

Example 2:数组

Given nums = [-2, -1, 2, 1]k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)post

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

给一个数组nums和一个目标值k,找出子数组和是k的最大长度,若是没有返回0.  要求O(n)时间复杂度。指针

解法1:双指针,双层循环计算全部的组合,判断是否和为k,若是是,更新max_len。时间复杂度高,TLEcode

解法:循环数组,用一个变量 cur_sum 记录到目前为止全部数组的和,若是等于k则更新max_len,在用一个 map 记录累加和的index,技巧:由于是求最长数组,因此一个和只记录第一次的index,之后出现的位置靠后,就不记录了。若是cur_sum在hashmap 中,表示当前位置去掉hashmap中记录的cur_sum - k的 index 的和等于k,  用两个index的差更新max_len。htm

Java:blog

public int maxSubArrayLen(int[] nums, int k) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 
    int max = 0;
    int sum=0;
    for(int i=0; i<nums.length; i++){
        sum += nums[i];
 
        if(sum==k){
            max = Math.max(max, i+1);
        }  
 
        int diff = sum-k;
 
        if(map.containsKey(diff)){
            max = Math.max(max, i-map.get(diff));
        }
 
        if(!map.containsKey(sum)){
            map.put(sum, i);
        }
    }
  
    return max;
}  

Python: Time:  O(n), Space: O(n)

class Solution(object):
    def maxSubArrayLen(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        sums = {}
        cur_sum, max_len = 0, 0
        for i in xrange(len(nums)):
            cur_sum += nums[i]
            if cur_sum == k:
                max_len = i + 1
            elif cur_sum - k in sums:
                max_len = max(max_len, i - sums[cur_sum - k])
            if cur_sum not in sums:
                sums[cur_sum] = i  # Only keep the smallest index.
        return max_len 

Python: wo

class Solution():
    def maxSubarry(self, nums, k):
        m = {0: -1}
        sm = 0
        for i in range(len(nums)):
            sm += nums[i]
            if sm not in m:
                m[sm] = i
            if sm - k in m:
                max_len = max(max_len, i - m[sm-k])

        return max_len  

C++:

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

  

相似题目:

[LeetCode] 53. Maximum Subarray 最大子数组

[LeetCode] 209. Minimum Size Subarray Sum 最短子数组之和

[LeetCode] 560. Subarray Sum Equals K 子数组和为K

Range Sum Query - Immutable

 

All LeetCode Questions List 题目汇总