16. 3Sum Closest

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

solution

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        cloest_sum = float('inf')
        cloest_dis = float('inf')

        for i in range(len(nums) - 2):
            l = i + 1
            r = len(nums) - 1

            while l < r:
                total_sum = nums[i] + nums[l] + nums[r]
                if abs(total_sum - target) < cloest_dis:
                    cloest_dis = abs(total_sum - target)
                    cloest_sum = total_sum

                if total_sum == target:                    
                    l += 1
                    r -= 1
                elif total_sum > target:
                    r -= 1
                else:
                    l += 1
        return cloest_sum

时间复杂度:O(n^2) 空间复杂度:O()

follow up

259. 3Sum Smaller

Last updated