您的位置:首页 > 其它

Subarray Sum

2015-11-29 15:09 363 查看
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].

Note

There is at least one subarray that it’s sum equals to zero.

有一个O(N)的解法。使用Map 来记录index, sum的值。当遇到两个index的sum相同时,表示从index1+1到index2是一个解。

注意:添加一个index = -1作为虚拟节点。这样我们才可以记录index1 = 0的解。

空间复杂度:O(N)

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) {
// write your code here

int len = nums.length;

ArrayList<Integer> ans = new ArrayList<Integer>();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

map.put(0, -1);

int sum = 0;
for (int i = 0; i < len; i++) {
sum += nums[i];

if (map.containsKey(sum)) {
ans.add(map.get(sum) + 1);
ans.add(i);
return ans;
}

map.put(sum, i);
}

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