Skip to content

Commit 7561b98

Browse files
committed
16. 3Sum Closest
1 parent 4d4acfc commit 7561b98

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Not only Leetcode solutions in Swift.
44

55
* [1.Two Sum](https://leetcode.com/problems/two-sum/)
66
* [15. 3Sum](https://leetcode.com/problems/3sum/)
7+
* [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/)
78
* [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
89
* [170. Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design)
910
* [Two Sum - Less than or equal to target](http://www.lintcode.com/en/problem/two-sum-less-than-or-equal-to-target/)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,44 @@ extension Solution {
9999

100100
let threeSumNums = [-1, 0, 1, 2, -1, -4]
101101
Solution.threeSum(nums: threeSumNums)
102+
103+
/**
104+
* 16. 3Sum Closest
105+
* https://leetcode.com/problems/3sum-closest/
106+
*/
107+
108+
extension Solution {
109+
class func threeSumClosest(nums: [Int]?, _ target: Int) -> Int?{
110+
guard let nums = nums, nums.count > 2 else { return nil }
111+
112+
let sortedNums = nums.sorted()
113+
var closestSum = nums[0] + nums[1] + nums[2]
114+
115+
for i in 0..<sortedNums.count - 1 {
116+
var left = i + 1
117+
var right = sortedNums.count - 1
118+
while (left < right) {
119+
let sum = sortedNums[i] + sortedNums[left] + sortedNums[right]
120+
if (abs(target - sum) < abs(target - closestSum)) {
121+
closestSum = sum
122+
}
123+
if (sum < target) {
124+
left += 1
125+
} else {
126+
right -= 1
127+
}
128+
}
129+
}
130+
131+
return closestSum
132+
}
133+
}
134+
135+
// usage
136+
137+
let threeSumClosestNums = [-1, 2, 1, -4]
138+
Solution.threeSumClosest(nums: threeSumClosestNums, 1)
139+
102140
/**
103141
* 167. Two Sum II - Input array is sorted
104142
* https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

0 commit comments

Comments
 (0)