成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LeetCode] 560. Subarray Sum Equals K

ccj659 / 2671人閱讀

Problem

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

Solution
class Solution {
    public int subarraySum(int[] nums, int k) {
        int sum = 0, res = 0;
        Map map = new HashMap<>();
        map.put(0, 1);
        int preSum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            preSum = sum-k;
            if (map.containsKey(preSum)) {
                res += map.get(preSum);
            }
            map.put(sum, map.getOrDefault(sum, 0)+1);
        }
        return res;
    }
}

//1, 2, 3, 4, 5, 6          k = 5
//1, 3, 6, 10, 15, 21

//1, 1, 1, 2, 1, 2, 1       k = 3
//1, 2, 3, 5, 6, 8, 9

//1, 2, 0, -1, 0, 1         k = 2
//1, 3, 3,  2, 2, 3

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/71854.html

相關(guān)文章

  • [LeetCode] Maximum Size Subarray Sum Equals k

    Problem Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isnt one, return 0 instead. Note The sum of the entire nums array is guaranteed to fit ...

    MudOnTire 評論0 收藏0
  • [LeetCode] 523. Continuous Subarray Sum

    Problem Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sum...

    stackfing 評論0 收藏0
  • [LeetCode] 862. Shortest Subarray with Sum at Leas

    摘要:較早放入的元素在隊列頂部最近放入的元素在隊列尾部檢查最近放入的,保證隊列中新放入的及對應(yīng)的均為遞增反證若保留,那么在下面第二個循環(huán),該元素有可能中斷循環(huán),并使得我們無法得到隊列更左邊的最優(yōu)解檢查較早放入的最小距離 Problem Return the length of the shortest, non-empty, contiguous subarray of A with sum...

    thursday 評論0 收藏0
  • leetcode 部分解答索引(持續(xù)更新~)

    摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個索引嘻嘻。 順序整理 1~50 1...

    leo108 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<