LeetCode - Subarray sum equals k

栏目: 编程工具 · 发布时间: 7年前

内容简介: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:Note:

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

解法一:利用sum之间的差暴力搜索

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

解法二:利用map建立sum和出现次数cnt的映射关系

class Solution {
    public int subarraySum(int[] nums, int k) {
        if (nums == null || nums.length == 0)
            return 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        int sum = 0, cnt = 0;
        for (int num : nums) {
            sum += num;
            cnt += map.getOrDefault(sum-k, 0);
            map.put(sum, map.getOrDefault(sum, 0)+1);
        }
        return cnt;
    }
}

第二种解法耗时更少

LeetCode - Subarray sum equals k


以上所述就是小编给大家介绍的《LeetCode - Subarray sum equals k》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Alone Together

Alone Together

Sherry Turkle / Basic Books / 2011-1-11 / USD 28.95

Consider Facebookit’s human contact, only easier to engage with and easier to avoid. Developing technology promises closeness. Sometimes it delivers, but much of our modern life leaves us less connect......一起来看看 《Alone Together》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具