반응형
📄 [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
반응형
'# 사용하지 않는 게시글 > 알고리즘 문제' 카테고리의 다른 글
[LeetCode] Combination Sum (0) | 2021.04.21 |
---|---|
[프로그래머스 - 탐욕법] 체육복 (0) | 2021.04.03 |
[LeetCode] 3Sum (0) | 2021.03.23 |
[LeetCode] Valid Parentheses (0) | 2021.03.21 |
[프로그래머스 - 구현] 자동완성 (for kakao) (0) | 2019.08.27 |
댓글