leetcode 560. Subarray Sum Equals K

257 篇文章 17 订阅

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:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

这道题还算简单。如果用 DP[i][j] 来做(i是子串的开始index,j是子串的结束index,DP[i][j] 存储 i ~ j 的和),会 Memory Limit Exceed.

需要注意的测试用例有两个。

1.

2.  [ -1, 1, 0, -1, 1]


这道题用最简单的方法就可以AC。

public int subarraySum(int[] nums, int k) {
	int count=0;		
	for(int begin=0;begin<nums.length;begin++){
		int sum=0;
		for(int end=begin;end<nums.length;end++){
			sum+=nums[end];
			if(sum==k){
				count++;
			}
		}
	}	
	return count;
}
这道题有solutions: https://leetcode.com/problems/subarray-sum-equals-k/solution/

Approach #2 Using Cummulative sum [Accepted]

Algorithm

我们定义了一个累积数组sum[], 其中sum[i] 存储了 0 ~ (i1)th index 的和。要想得到 SUM[i, j],只需要知道 SUM[0, i - 1] 和 SUM[0, j] 就好了。SUM[~jsum[j+1] - sum[i]sum[j]sum[i-1].

Java

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

Complexity Analysis

  • Time complexity : O(n^2)O(n2). Considering every possible subarray takes O(n^2)O(n2) time. Finding out the sum of any subarray takes O(1)O(1) time after the initial processing of O(n)O(n) for creating the cumulative sum array.

  • Space complexity : O(n)O(n). Cumulative sum array sumsum of size n+1n+1 is used.


Approach #3 Without space [Accepted]

Algorithm

这个解法跟我的解法是一样的。选择一个特定的startstart 点,遍历其之后的 endend 点。计算从 start ~ end 的 sum。当 sumsum = kk 时,更新 countcount 值。

Java

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        for (int start = 0; start < nums.length; start++) {
            int sum=0;
            for (int end = start; end < nums.length; end++) {
                sum+=nums[end];
                if (sum == k)
                    count++;
            }
        }
        return count;
    }
}

Complexity Analysis

  • Time complexity : O(n^2)O(n2). We need to consider every subarray possible.

  • Space complexity : O(1)O(1). Constant space is used.


Approach #4 Using hashmap [Accepted]

Algorithm

we know the key to solve this problem is SUM[i, j]. So if we know SUM[0, i - 1] and SUM[0, j], then we can easily get SUM[i, j]. To achieve this, we just need to go through the array, calculate the current sum and save number of all seen PreSum to a HashMap. Time complexity O(n), Space complexity O(n).

Java

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int sum = 0, count= 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)) {
                count += preSum.get(sum - k);
            }
            preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
        }
        
        return count;
    }
}

Complexity Analysis

  • Time complexity : O(n)O(n). The entire numsnums array is traversed only once.

  • Space complexity : O(n)O(n). Hashmap mapmap can contain upto nn distinct entries in the worst case.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值