본문 바로가기
#알고리즘 [Algorithm]/Problem

[LeetCode] 3Sum Closest

by cy_mos 2021. 3. 23.
반응형

📄 [LeetCode] 3Sum Closest

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.

 

class Solution {
    func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
        var result: (Int, Int) = (Int.max, Int.zero)
    let sortedNums: Array<Int> = nums.sorted()
    
    for index in Int.zero..<nums.count {
        var left: Int = index + 1, right: Int = nums.count - 1
        while left < right {
            let closest = sortedNums[left] + sortedNums[right] + sortedNums[index]
            
            if result.0 > abs(closest - target) {
                result = (abs(closest - target), closest)
            }
            
            if closest - target < Int.zero { left += 1 }
            else { right -= 1 }
        }
    }
    
    return result.1
    }
}

🚀 REFERENCE

 

반응형

댓글