Skip to content

Commit 16fcb5c

Browse files
committed
和为0的子数组
1 parent 8a93f07 commit 16fcb5c

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@
189189
- [Stone Game](/algorithm/LeetCode/Dynamic-Programming/Stone-Game.md)
190190
- [Array](/algorithm/LeetCode/Array.md)
191191
- [Partition Array](/algorithm/LeetCode/Array/Partition-Array.md)
192+
- [Subarray Sum](/algorithm/LeetCode/Array/Subarray-Sum.md)
192193

193194
## 设计模式
194195

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
## 一、题目
2+
3+
> Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.
4+
>
5+
> **Example**
6+
>
7+
> Given `[-3, 1, 2, -3, 4]`, return `[0, 2]` or `[1, 3]`.
8+
9+
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
10+
11+
## 二、解题思路
12+
13+
记录每一个位置的sum,存入HashMap中,如果某一个sum已经出现过,那么说明中间的subarray的sum为0. 时间复杂度O(n),空间复杂度O(n)
14+
15+
## 三、解题代码
16+
17+
```java
18+
public class Solution {
19+
/**
20+
* @param nums: A list of integers
21+
* @return: A list of integers includes the index of the first number
22+
* and the index of the last number
23+
*/
24+
public ArrayList<Integer> subarraySum(int[] nums) {
25+
// write your code here
26+
27+
int len = nums.length;
28+
29+
ArrayList<Integer> ans = new ArrayList<Integer>();
30+
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
31+
32+
map.put(0, -1);
33+
34+
int sum = 0;
35+
for (int i = 0; i < len; i++) {
36+
sum += nums[i];
37+
38+
if (map.containsKey(sum)) {
39+
ans.add(map.get(sum) + 1);
40+
ans.add(i);
41+
return ans;
42+
}
43+
44+
map.put(sum, i);
45+
}
46+
47+
return ans;
48+
}
49+
}
50+
```
51+

0 commit comments

Comments
 (0)