Subarray Sum Closet

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.