최대 1 분 소요

Python

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        sorted_nums = sorted(nums)
        answer = sorted_nums[0] + sorted_nums[1] + sorted_nums[2]
        for i in range(len(nums) - 1):
            left = i + 1
            right = len(nums) - 1
            while left < right:
                current = sorted_nums[i] + sorted_nums[left] + sorted_nums[right]
                if answer == target:
                    return answer
                if abs(answer - target) > abs(current - target):
                    answer = current
                if current < target:
                    left += 1
                else:
                    right -= 1
        
        return answer

댓글남기기