Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前缀和技巧c++版本 #306

Merged
merged 5 commits into from
Jun 22, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
增加CPP版本
  • Loading branch information
Jasper-Joe committed Jun 22, 2020
commit 47409bee5cbf77c8a04129e4d8c5033a3defbefe
55 changes: 54 additions & 1 deletion 算法思维系列/前缀和技巧.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Integer, Integer>
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<int>& nums, int k) {
int n=nums.size();
unordered_map<int,int> preSum;
// map: 前缀和 -> 该前缀和出现的次数
preSum[0]=1; // base case: 例如当数组中只有一个元素, 而k恰好等于这个元素
int ans=0, sum0_i=0; // sum0_i 表示前缀和 nums[0...i]
for(int i=0;i<n;i++)
{
sum0_i +=nums[i];
// 这是我们想找的前缀和 nums[0...j]
int sum0_j=sum0_i-k;
// 如果前面有这个前缀和,则直接更新答案
if(preSum.count(sum0_j))
ans+=preSum[sum0_j];
//把前缀和 nums[0...i] 加入并记录出现次数
preSum[sum0_i]++; // 把当前的前缀和加入到map中
}
return ans;
}
};
```

[上一篇:烧饼排序](../算法思维系列/烧饼排序.md)

[下一篇:字符串乘法](../算法思维系列/字符串乘法.md)

[目录](../README.md#目录)
[目录](../README.md#目录)