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.
java
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 List<Integer> subarraySum(int[] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return null;
}
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
map.put(0, -1);
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (map.containsKey(sum)) {
list.add(map.get(sum) + 1);
list.add(i);
break;
} else {
map.put(sum, i);
}
}
return list;
}
}
python
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
"""
def subarraySum(self, nums):
# write your code here
if nums is None or len(nums) == 0:
return []
summary, mapping, arr = 0, {}, []
mapping[0] = -1
for i in range(len(nums)):
summary += nums[i]
if summary in mapping:
arr.append(mapping[summary] + 1)
arr.append(i)
break
else:
mapping[summary] = i
return arr