Leetcode 560: Subarray Sum Equal k

Leetcode 560

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].

方法

public class Solution {
    public int subarraySum(int[] nums, int k) {

    }
}

解答


1. Brute Force (start-end)

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;

        return count;
    }
}

(time limit exceeded)


2. cumulative sum (累加和)

注意连续二字
sum[i] 表示nums中前i个数之和
sum[j] - sum[i] (j>i)表示i~j的累加和
所以先求出sum[i]

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

accepted


3. Start-End pro

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;
    }
}

4. HashMap

前几个方法都还不错,但时间上很昂贵。

在累加和方法的基础上,使用HashMap存储

key: 累加和的值,value: 所求累加和为该值的个数

sum[i] = sum[j]-k,使用HashMap查询sum-k的值是否存于HashMap中
若存在,count值加上sum-k对应的value值。

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
        hashmap.put(0,1); // 0,一个也不加
        int sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            if(hashmap.containsKey(sum-k)){
                count += hashmap.get(sum-k);
            }
            hashmap.put(sum, hashmap.getOrDefault(sum,0)+1);
        }
        return count;
    }
}

由上到下:4,3,2,1方法时间对比
4,3,2,1时间对比

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值