파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 10. 8. 23:45

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

6번 WA 받고 그냥 솔루션 봄 -_-
조건이 좀 까다로운 것 같았는데.. sliding window를 이용하면 되는 거 였던듯.

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        res = nums[0] + nums[1] + nums[2]
        
        for i in range(len(nums)-2):
            j, k = i+1, len(nums) - 1
            
            while j < k:
                sum = nums[i] + nums[j] + nums[k]
                
                if sum == target:
                    return sum
                
                if abs(sum-target) < abs(res-target):
                    res = sum
                    
                if sum < target:
                    j += 1
                elif sum > target:
                    k -= 1
                else:
                    return res
        return res
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.10.10
Today's Challenge  (0) 2022.10.09
Today's Challenge  (0) 2022.10.07
Today's Challenge  (0) 2022.10.06
Today's Challenge  (0) 2022.10.05
Comments