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]
.
This question sums the subarray nearest 0, which belongs to the follow up of Subarray sum. The idea is also very similar, each time you ask for the current position and the previous array of one and. But this question is not equal to 0, will not have the same and appear, so use HashMap is not possible.
In this case, maintain an array of a <sum,index> pair, ordering the array by the sum value. The index of the lowest absolute value of the interpolated value for the adjacent position in the sorted array. The small one is the index at the beginning of the Subarray, and the larger is the index at the end. Complexity Analysis:
1. Find the pair array time complexity O (n) of the
2. Sort O (Nlogn)
3. Adjacent to each other O (n)
The overall time complexity is O (n) and the spatial complexity is O (n).
Note
classSolution:"""@param nums:a List of integers @return: A list of integers includes the index of the first number The index of the last number""" defsubarraysumclosest (Self, nums):#Pointerres =[] Sum=0 forIinchxrange (len (nums)): Sum+=Nums[i] Res.append ((sum,i)) res.sort (Key = Lambda x:x[0]) left=-1 Right=0 diff=ABS (res[0][0]) forIinchXrange (1,len (nums)-1): ifABS (Res[i][0]-res[i-1][0]) <Diff:left= Min (res[i-1][1], res[i][1]) right= Max (res[i-1][1], res[i][1]) diff= ABS (Res[i][0]-res[i-1][0])return[Left+1, right]
Subarray Sum Closet