From 47409bee5cbf77c8a04129e4d8c5033a3defbefe Mon Sep 17 00:00:00 2001 From: jasper Date: Sun, 21 Jun 2020 20:57:31 -0400 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0CPP=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...00\345\222\214\346\212\200\345\267\247.md" | 55 ++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\211\215\347\274\200\345\222\214\346\212\200\345\267\247.md" "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\211\215\347\274\200\345\222\214\346\212\200\345\267\247.md" index 98960c0..2e25044 100644 --- "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\211\215\347\274\200\345\222\214\346\212\200\345\267\247.md" +++ "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\211\215\347\274\200\345\222\214\346\212\200\345\267\247.md" @@ -133,9 +133,62 @@ for (int i = 1; i < count.length; i++) ![labuladong](../pictures/labuladong.jpg) +[labuladong](https://github.com/labuladong) 提供JAVA解法代码: + +``` +int subarraySum(int[] nums, int k) { + int n = nums.length; + // map:前缀和 -> 该前缀和出现的次数 + HashMap + preSum = new HashMap<>(); + // base case + preSum.put(0, 1); + + int ans = 0, sum0_i = 0; + for (int i = 0; i < n; i++) { + sum0_i += nums[i]; + // 这是我们想找的前缀和 nums[0..j] + int sum0_j = sum0_i - k; + // 如果前面有这个前缀和,则直接更新答案 + if (preSum.containsKey(sum0_j)) + ans += preSum.get(sum0_j); + // 把前缀和 nums[0..i] 加入并记录出现次数 + preSum.put(sum0_i, + preSum.getOrDefault(sum0_i, 0) + 1); + } + return ans; +} +``` + +[Jinglun Zhou](https://github.com/Jasper-Joe) 提供C++解法代码: + +```CPP +class Solution { +public: + int subarraySum(vector& nums, int k) { + int n=nums.size(); + unordered_map preSum; + // map: 前缀和 -> 该前缀和出现的次数 + preSum[0]=1; // base case: 例如当数组中只有一个元素, 而k恰好等于这个元素 + int ans=0, sum0_i=0; // sum0_i 表示前缀和 nums[0...i] + for(int i=0;i