您的位置:首页 > 其它

*[Lintcode] Subarray Sum

2016-04-16 17:09 211 查看
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.

Example

Given 
[-3, 1, 2, -3, 4]
,
return 
[0, 2]
 or 
[1,
3]
.
考虑特殊情况, 即只有0, 区间从0开始和区间从中间开始。

public class Solution {
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
public ArrayList<Integer> subarraySum(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
map.put(0, -1);
int sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
if(map.containsKey(sum)) {
res.add(i);
res.add(map.get(sum) + 1);
return res;
}

map.put(sum, i);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode