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.

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)

方法一:双指针
时间复杂度:O(n^2)
空间复杂度:O(1)

public int maxSubArrayLen(int[] nums,int k){
        int length = nums.length;
        int max = 0;
        for(int i = 0;i < length;i++){
            int sum = 0;
            for(int j = i;j < length;j++){
                sum+=nums[j];
                if(sum == k){
                    max = Math.max(max,(j - i + 1));
                }
            }
        }
        return max;
    }

方法二:
出现的结果只会有三种情况:
1.从头遍历到尾,没有任何情况存在子数组累加和 = k。
2.从i = 0开始遍历,到 j 位置时,nums[i] + … + nums[j] = k成立。
3.从i(i != 0)开始遍历,到j位置,结果成立。

public int maxSubArrayLen1(int[] nums,int k) {
        int length = nums.length;
        Map<Integer,Integer> map = new HashMap<>();
        int sum = 0;
        int max = 0;
        for(int i = 0;i < length;i++){
            sum += nums[i];
            if(sum == k){
                max = i + 1;
            }else if(map.containsKey(sum - k)){
                max = Math.max(max,(i - map.get(sum - k)));
            }else{
                map.put(sum,i);
            }
        }
        for(Map.Entry entry:map.entrySet()){
            System.out.println("key:"+entry.getKey()+" value:"+entry.getValue());
        }

        return max;
    }

你可能感兴趣的:(#双指针)