29ms O(n) Java solution


  • 0
    L
    public class Solution {
        public int maxSubArrayLen(int[] nums, int k) {
            int sum = 0;
            int maxLength = 0;
            HashMap hm = new HashMap();
            for (int i=0;i<nums.length;i++){
                sum += nums[i];
                //判断当前累积和是否为k,为k的话,当前长度为i+1([0,i])
                if (sum == k){
                    maxLength = Math.max(maxLength,i+1);
                }
                else{
                    //判断当前累积和与k的差是否在hashmap里存在,若存在则当前子串长度为i-j,j为差值的下标
                    if (hm.containsKey(sum-k)){
                        maxLength = Math.max(maxLength,i-(int)hm.get(sum-k));
                    }
                }
                
                if (!hm.containsKey(sum))
                hm.put(sum,i);               
            }
            
            return maxLength;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.