您的位置:首页 > 其它

(138)子数组之和

2015-10-22 14:01 288 查看


容易 子数组之和
查看运行结果 

25%

通过

给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置

您在真实的面试中是否遇到过这个题? 

Yes

样例

给出[-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].
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 static ArrayList<Integer> subarraySum(int[] nums) {

ArrayList<Integer> list = new ArrayList<Integer>();
int len =nums.length;
int i = 0;
boolean flag = true;
while(i<len && flag)
{
int sum = nums[i];
if(sum==0)
{
list.add(i);
list.add(i);
flag = false;
}
else{
for(int j=i+1;j<len;j++)
{
sum += nums[j];
if(sum == 0)
{
list.add(i);
list.add(j);
flag = false;
break;
}
}
}
i++;
}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: