Subarray Sum Closest – Python 3 (Week 13 – 11)

class Solution:
    """
    @param: nums: A list of integers
    @return: A list of integers includes the index of the first number and the index of the last number
    """
    def subarraySumClosest(self, nums):
        
        # write your code here
        if not nums:
            return []
            
        nowsum = 0
        sumindex = [[0, -1]]
        for i in range(len(nums)):
            nowsum += nums[i]
            sumindex.append((nowsum, i))
        
        sumindex.sort(key=lambda x : x[0])
        
        dis = float('inf')
        start, end = 0, 0
        
        for i in range(len(sumindex) - 1):
           if sumindex[i + 1][0] - sumindex[i][0] < dis:
                start = sumindex[i + 1][1]
                end = sumindex[i][1]
                dis = sumindex[i + 1][0] - sumindex[i][0]
                
        if start == end:
            return [start, end]
        elif start < end:
            return [start + 1, end]
        else:
            return [end + 1, start]

Time O(nlogn). Space O(n).

Leave a comment

Design a site like this with WordPress.com
Get started