zoukankan      html  css  js  c++  java
  • LeetCode-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?

     
    Analysis:
     
    Use a HashMap to store pair of <sum val, ind>, then for each sum[i], we query whether there is <sum[i]-k, x>, if yes, then we found one candidate.
     
    Solution:
     1 public class Solution {
     2     public int maxSubArrayLen(int[] nums, int k) {
     3         int res = 0, len = nums.length;
     4         Map<Integer,Integer> sumMap = new HashMap<Integer,Integer>();        
     5 
     6         int sum=0;
     7         for (int i=0;i<len;i++){
     8             sum += nums[i];
     9             if (sum==k) {
    10                 res = i+1;
    11             } else if (sumMap.containsKey(sum-k)){
    12                 res = Math.max(res, i-sumMap.get(sum-k));
    13             }
    14             if (!sumMap.containsKey(sum)){
    15                 sumMap.put(sum,i);
    16             }    
    17         }
    18 
    19         return res;
    20     }
    21 }
  • 相关阅读:
    Docker多主机互联
    数据结构
    广度优先算法走出迷宫
    golang反射
    waitGroup的使用
    golang中的mutex锁
    goroutine和channel
    如何优雅的关闭Golang Channel?
    使用context关闭协程以及协程中的协程
    golang对不同系统的编译
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5764485.html
Copyright © 2011-2022 走看看