띠리링구 2022. 11. 4. 03:01

https://leetcode.com/problems/3sum-closest/

 

3Sum Closest - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

내가 예전에 풀어놓은 솔루션이 너무 잘푼거같다.

 

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        
        nums.sort()
        
        closest = nums[0] + nums[1] + nums[2]
    
        length = len(nums)
        for i in range(length-2):
            l = i + 1
            r = length - 1
            
            while l < r:
                sum3 = nums[l] + nums[r] + nums[i]
                if abs(sum3-target)<abs(closest-target):
                    closest = sum3
                
                if sum3 > target:
                    r -= 1
                elif sum3 < target:
                    l += 1
                else :
                    return target
        return closest