leetcode560. Subarray Sum Equals K

来源:互联网 发布:澳大利亚淘宝 编辑:程序博客网 时间:2024/06/02 04:07

560. Subarray Sum Equals K

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

解法一

暴力法,两层循环,判断以每一个元素开头一直累加是否能和k相等。

public class Solution {    public int subarraySum(int[] nums, int k) {        if (nums == null || nums.length == 0) {            return 0;        }        int sum  = 0, count = 0;        for (int i = 0; i < nums.length; i++) {            sum = 0;            sum += nums[i];            if (sum == k) {                count++;            }            for (int j = i + 1; j < nums.length; j++) {                sum += nums[j];                if (sum == k) {                    count++;                }            }        }        return count;    }}

解法二

遍历数组,累加到每一个元素的sum添加到map中,得到0, sum0,sum1,sum2, …., sum(n-1).如果sumj - sumi = k,即可得sum(i+1…j)为k,即计数+1。

public class Solution {    public int subarraySum(int[] nums, int k) {        if (nums == null || nums.length == 0) {            return 0;        }        int sum = 0, result = 0;        Map<Integer, Integer> 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);            }            if (preSum.containsKey(sum)) {                preSum.put(sum, preSum.get(sum) + 1);            } else {                preSum.put(sum, 1);            }        }        return result;    }}
原创粉丝点击