Given an array of integers, locate and zero the sub-array. Your code should return the starting and ending positions of the subarray that meet the requirements
Sample Example
Given [ -3, 1, 2, -3, 4], return [0, 2] or [1, 3].
Idea: This problem at the beginning of my idea is to use a two-way propaganda to find the first set of consecutive numbers and 0 of the ends, you will find that the complexity of the algorithm is O (n*n); it should be a very complicated method, and then we see this algorithm, we start from the first, to each element of the first n and find out, When sum (j) =sum (i) (J>i) appears, the sum of items i+1 to J is considered to be 0; this is a very ingenious algorithm. So we set up an array of the first n items and we can get the results once in a sort order. Complexity of O (NLOGN)
1 classElementImplementsComparable<element>{2 intindex;3 intvalue;4 PublicElement (intIintv) {5index =i;6Value =v;7 }8 Public intCompareTo (Element other) {9 return This. value-Other.value;Ten } One Public intGetIndex () { A returnindex; - } - Public intGetValue () { the returnvalue; - } - } - Public classSolution { + /** - * @paramnums:a List of integers + * @return: A list of integers includes the index of the first number A * The index of the last number at */ - PublicArraylist<integer> Subarraysum (int[] nums) { - //Write your code here -arraylist<integer> res =NewArraylist<integer>(); - if(Nums = =NULL|| Nums.length = = 0)returnRes; - intLen =nums.length; inElement[] sums =NewElement[len+1]; -sums[0]=NewElement ( -1,0); to intSum =0; + for(inti=0;i<len;i++){ -Sum + =Nums[i]; thesums[i+1]=NewElement (i,sum); * } $ Arrays.sort (sums);Panax Notoginseng for(inti=0;i<len;i++){ - if(Sums[i].getvalue () ==sums[i+1].getvalue ()) { the intm = Math.min (Sums[i].getindex (), Sums[i+1].getindex ()) +1; + intn = Math.max (Sums[i].getindex (), sums[i+1].getindex ()); A Res.add (m); the Res.add (n); + returnRes; - } $ } $ returnRes; - } -}
The sum of the sub-arrays