给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
样例
给出 [-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].
注意事项
There is at least one subarray that it's sum equals to zero.
解题思路1:
常规思路是循环扫描,时间复杂度O(n^2),不可取
注意[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 List<Integer> subarraySum(int[] nums) {
// write your code here
if(nums == null || nums.length == 0)
return null;
List<Integer> res = new ArrayList<>();
if(nums.length == 1 && nums[0] == 0){
res.add(0);
res.add(0);
return res;
}
for(int i=0; i<nums.length; i++){
int sum = nums[i];
int first = i;
int end = i;
for(int j=i+1; j<nums.length; j++){
if(sum == 0){
res.add(first);
res.add(end);
return res;
}
sum += nums[j];
end = j;
if(sum == 0){
res.add(first);
res.add(end);
return res;
}
}
}
return res;
}
}
解题思路2:
如果有子数组[i,j]和为零,则表示前i个元素之和(不包括i) == 前j个元素之和(包括j)
用HashMap存储,key表示依次的和,value表示当前和的下标
当碰到相同和的时候则代表找到和为零的子数组
注意初始化:map.put(0, -1),这样可以记录下标==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 List<Integer> subarraySum(int[] nums) {
// write your code here
if(nums == null || nums.length == 0)
return null;
List<Integer> res = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int sum = 0;
for(int i=0; i<nums.length; i++){
sum += nums[i];
if(map.containsKey(sum)){
res.add(map.get(sum) + 1);
res.add(i);
break;
}else{
map.put(sum, i);
}
}
return res;
}
}
本文介绍了一种高效算法,用于在整数数组中找到和为零的子数组,通过使用HashMap存储累计和及其对应的下标,实现O(n)的时间复杂度。文章提供了详细的解题思路和代码实现。
697

被折叠的 条评论
为什么被折叠?



