560. Subarray Sum Equals K leetcode

这道题,BF 时间复杂度O(n^2)

public static int subarraySum(int[] nums, int k) {
        long [][] map = new long [nums.length+1][nums.length+1];
        long[] odd = new long[nums.length+1];
        long[] even = new long[nums.length+1];
        int sum = 0;
        for(int i=1;i<=nums.length;i++){
            odd[i] = odd[i-1]+nums[i-1];
        }
        boolean flag = true;
        for(int i=1;i<=nums.length;i++){

            for(int j=i;j<=nums.length;j++){
                int last = 0;
                if(i==1) last = 0;
                else     last = nums[i-2];
                if(flag){
                    even[j] = odd[j]-last;
                    if(even[j]==k) sum++;
                }else{
                    odd[j] = even[j] -last;
                    if(odd[j]==k) sum++;
                }
            }
            flag = !flag;
        }
        return sum;
     }

如果开多个数组会SLE
可以用hashMap 时间复杂度O(n);

public static int subarraySum(int[] nums, int k) {
    int sum = 0, result = 0;
        Map preSum = new HashMap<>();
        preSum.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (preSum.containsKey(sum - k)) {
                result += preSum.get(sum - k);
            }
            preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
        }
        return result;
    }

思路关键在于hashmap中存放的是0-i 的sum
若sum - target 存在即为存在0-n sum[n] = sum-target;

你可能感兴趣的:(java,leetcode-java,leetcode)