Skip to content

Latest commit

 

History

History
43 lines (31 loc) · 1.25 KB

16.-3sum-closest.md

File metadata and controls

43 lines (31 loc) · 1.25 KB

16. 3Sum Closest

  • Medium

  • Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

    Return the sum of the three integers.

    You may assume that each input would have exactly one solution.

Analysis

This problem has a similar build up like problem 15.-3sum.md. But here we might not find the set of numbers that adds up to be the target, therefore we keep an record of the minimal difference each time we try.

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        n=len(nums)
        answer=[]
        mini=float('inf')
        for i in range(n):
            temp=target-nums[i]
            l=i+1
            r=n-1
            while l<r:
                currsum=nums[l]+nums[r]-temp

                if abs(mini)>abs(currsum):
                        mini=currsum
                        
                if currsum==0:
                    return target;

                elif currsum<0:
                    l+=1

                else:
                    r-=1

        return target+mini