diff --git a/bishoe01/README.md b/bishoe01/README.md index d4e826f..92897cf 100644 --- a/bishoe01/README.md +++ b/bishoe01/README.md @@ -6,4 +6,5 @@ | 2차시 | 2025.04.09 | DP | [1277. Count Square Submatrices with All Ones](https://leetcode.com/problems/count-square-submatrices-with-all-ones/description/?envType=problem-list-v2&envId=dynamic-programming)|https://github.com/AlgoLeadMe/AlgoLeadMe-14/pull/11| | 3차시 | 2025.04.30 | DP | [1267. Count Servers that Communicate](https://leetcode.com/problems/count-servers-that-communicate/description/?envType=daily-question&envId=2025-04-29)|https://github.com/AlgoLeadMe/AlgoLeadMe-14/pull/16| | 4차시 | 2025.05.09 | 문자열 | [1839. Longest Substring Of All Vowels in Order](https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/description/)|https://github.com/AlgoLeadMe/AlgoLeadMe-14/pull/19| +| 5차시 | 2025.05.23 | 정렬, 투포인터 | [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/description/)|https://github.com/AlgoLeadMe/AlgoLeadMe-14/pull/28| --- diff --git "a/bishoe01/\354\240\225\353\240\254/3Sum Closest.swift" "b/bishoe01/\354\240\225\353\240\254/3Sum Closest.swift" new file mode 100644 index 0000000..08cb529 --- /dev/null +++ "b/bishoe01/\354\240\225\353\240\254/3Sum Closest.swift" @@ -0,0 +1,42 @@ +import Foundation + +// abs(sum - target)가 가장 작은애 찾기 + +class Solution { + func threeSumClosest(_ nums: [Int], _ target: Int) -> Int { + func caculate(_ sum: Int) -> Int { + return abs(sum - target) + } + +// var answer = 3000 // 최대값 범위 3개 더한 것 으로 해줬는데, target이 높아서 이렇게 해주면 틀리다고 뜸 ! +// var answer = Int.max // 터짐 - max값에 +가 조금이라도 되니까 펑 터져버리는 이슈가 있음 + var answer = Int(Int32.max) // 그래서 그나마 값이 조금 작은 큰값으로 해결 + var nums = nums + nums.sort(by: <) + let LEN = nums.count + for i in 0 ..< LEN - 2 { + var left = i + 1 + var right = LEN - 1 + while left < right { + let totalSum = nums[i] + nums[left] + nums[right] +// print(nums[i], nums[left], nums[right]) +// print(totalSum) +// print(caculate(totalSum)) + if caculate(totalSum) < caculate(answer) { +// print(nums[i], nums[left], nums[right]) + answer = totalSum + } + if totalSum < target { + left += 1 + } else if totalSum > target { + right -= 1 + } else { + return target + } + } + } + return answer + } +} + +print(Solution().threeSumClosest([1, 1, 1, 1], -100))