LeetCode每日一题560. 和为K的子数组(前缀和)

331 阅读1分钟

地址:leetcode-cn.com/problems/su…

前缀和+hash表
前缀和的定义:[i..j]的和可以写成preSum[j]-preSum[i-1]
public int subarraySum2(int[] nums, int k) {
        int preSum = 0;
        int count = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        //会有元素本身就等于K,那么K+0算一次
        map.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            preSum += nums[i];
            if (map.containsKey(preSum - k)) {
                count += map.get(preSum - k);
            }
            map.put(preSum, map.getOrDefault(preSum, 0) + 1);
        }
        return count;
    }

暴力法,枚举边界

public int subarraySum(int[] nums, int k) {
        int count = 0;
        //固定左边界不动,从右边界开始枚举和
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j >= 0; j--) {
                sum += nums[j];
                if (sum == k) {
                    count++;
                }
            }
        }
        return count;
    }