(138)子陣列之和
阿新 • • 發佈:2019-01-25
容易 子陣列之和
25% 通過給定一個整數陣列,找到和為零的子陣列。你的程式碼應該返回滿足要求的子陣列的起始位置和結束位置
給出[-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; } }