Question
Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.
Given [-3, 1, 1, -3, 5]
, return [0, 2]
, [1, 3]
, [1, 1]
, [2, 2]
or [0, 4]
.
Answer
This question continues the idea of subarray sum, and the sum of [0, I] will be saved up. This constructs a new class, Pair. The sum value is stored on one hand and the index is saved. The difference between the adjacent sum value is then sorted according to the sum value. The minimum difference is the result. The time complexity is O (Nlogn), and the spatial complexity is O (n).
Note: Assuming that the difference between the sum value of [0-2] and [0-4] is minimal, then the result is index[3,4]
1 Public classSolution {2 3 classPair {4 Public intsum;5 Public intindex;6 PublicPair (intSumintindex) {7 This. sum =sum;8 This. index =index;9 }Ten } One /** A * @paramnums:a List of integers - * @return: A list of integers includes the index of the first number - * The index of the last number the */ - Public int[] Subarraysumclosest (int[] nums) { - //Write your code here - int[] result =New int[2]; + if(Nums = =NULL|| Nums.length = = 0) { - returnresult; + } A intLen =nums.length; at intsum = 0; -list<pair> list =NewArraylist<pair>(); - for(inti = 0; i < Len; i++) { -Sum + =Nums[i]; -Pair tmp =NewPair (sum, i); - List.add (TMP); in } -Collections.sort (list,NewComparator<pair>() { to Public intCompare (pair A, pair B) { + return(A.sum-b.sum); - } the }); * intMin =Integer.max_value; $ for(inti = 1; i < Len; i++) {Panax Notoginseng intdiff = List.get (i). Sum-list.get (i-1). Sum; - if(diff <min) { theMin =diff; + intIndex1 =List.get (i). Index; A intIndex2 = List.get (i-1). Index; the if(Index1 <index2) { +Result[0] = index1 + 1; -RESULT[1] =Index2; $}Else { $Result[0] = index2 + 1; -RESULT[1] =index1; - } the } - }Wuyi returnresult; the } -}
Subarray Sum Closest