ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 16. 3Sum Closest
    Leetcode 2021. 5. 6. 17:15

    Given an array nums of n integers 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.

     

    Example 1:

    Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

     

    Constraints:

    • 3 <= nums.length <= 10^3
    • -10^3 <= nums[i] <= 10^3
    • -10^4 <= target <= 10^4
    class Solution(object):
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            
            nums = sorted(nums)
    
            res = nums[0]+nums[1]+nums[2]
    
            for i in range(0, len(nums)):
                left = i+1
                right = len(nums)-1
    
                while left < right:
                    sums = nums[i] + nums[left] + nums[right]
    
                    if sums == target:
                        return sums
                    elif abs(target - res) > abs(target - sums):
                        res = sums        
                    if sums < target:
                        left += 1
                    elif sums > target:
                        right -=1
                        
            return res
    

     

    15번 문제와 비슷하게 2개의 포인터를 사용하면 쉽게 풀 수 있었다.

    'Leetcode' 카테고리의 다른 글

    18. 4Sum  (0) 2021.05.10
    17. Letter Combinations of a Phone Number  (0) 2021.05.10
    15. 3Sum  (0) 2021.05.06
    14. Longest Common Prefix  (0) 2021.05.06
    Leetcode 13. Roman to Integer  (0) 2021.05.04
Designed by Tistory.