Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.
Example
Given [ -3, 1, 1, -3, 5], return [0, 2], [1, 3], [1, 1], [2, 2] or [0, 4]
Challenge
O (NLOGN) time
Analysis:
S[i] = Nums[0]+....nums[i], also record the index i into s[i]. Sort array s, and the minimum difference between-consecutive element, is the the The Subarray.
Solution:
1 classElementImplementsComparable<element>{2 intVal;3 intindex;4 PublicElement (intVinti) {5val =v;6index =i;7 }8 9 Public intCompareTo (Element other) {Ten return This. Val-Other.val; One } A - Public intGetIndex () { - returnindex; the } - - Public intGetValue () { - returnVal; + } - } + A Public classSolution { at /** - * @paramnums:a List of integers - * @return: A list of integers includes the index of the first number - * The index of the last number - */ - PublicArraylist<integer> Subarraysumclosest (int[] nums) { inarraylist<integer> res =NewArraylist<integer>(); - if(nums.length==0)returnRes; to +Element[] sums =NewElement[nums.length+1]; -Sums[0] =NewElement (0,-1); the intsum = 0; * for(inti=0;i<nums.length;i++){ $Sum + =Nums[i];Panax NotoginsengSUMS[I+1] =NewElement (sum,i); - } the + Arrays.sort (sums); A intmin = Math.Abs (Sums[0].getvalue ()-sums[1].getvalue ()); the intStart = Math.min (Sums[0].getindex (), Sums[1].getindex ()) +1; + intEnd = Math.max (Sums[0].getindex (), sums[1].getindex ()); - for(inti=1;i<nums.length;i++){ $ intdiff = Math.Abs (sums[i].getvalue ()-sums[i+1].getvalue ()); $ if(diff<min) { -Min =diff; -Start = Math.min (Sums[i].getindex (), Sums[i+1].getindex ()) +1; theEnd = Math.max (Sums[i].getindex (), sums[i+1].getindex ()); - }Wuyi } the - Res.add (start); Wu Res.add (end); - returnRes; About } $}
Lintcode-subarray Sum Closest