GuilinDev

Lc0325

05 August 2008

325 Maximum Size Subarray Sum Equals k $

和等于k的最长子数组长度 - Hashmap

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        int sum = 0, max = 0;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            sum = sum + nums[i];
            if (sum == k) max = i + 1;
            else if (map.containsKey(sum - k)) max = Math.max(max, i - map.get(sum - k));
            if (!map.containsKey(sum)) map.put(sum, i);
        }
        return max;
    }
}