Skip to content

Commit

Permalink
016-3sum-closest
Browse files Browse the repository at this point in the history
  • Loading branch information
bofeizhu committed Aug 10, 2018
1 parent 2022478 commit c088cc8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 016-3sum-closest.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/// 16. 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.

import XCTest

// Approach: Two Pointers
func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
guard nums.count > 2 else { fatalError() }
let nums = nums.sorted()
var closestSum = nums[0] + nums[1] + nums[2]
for i in 0...nums.count - 3 {
var head = i + 1
var tail = nums.count - 1
while head < tail {
let sum = nums[i] + nums[head] + nums[tail]

// update pointers
if sum == target {
return target
} else if sum > target {
tail -= 1
} else {
head += 1
}

// update closest sum
closestSum = abs(sum - target) < abs(closestSum - target) ? sum : closestSum
}
}
return closestSum
}

class Tests: XCTestCase {
func testExample() {
let nums = [-1, 2, 1, -4]
XCTAssertEqual(threeSumClosest(nums, 1), 2)
}
}

Tests.defaultTestSuite.run()
4 changes: 4 additions & 0 deletions 016-3sum-closest.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos' executeOnSourceChanges='false'>
<timeline fileName='timeline.xctimeline'/>
</playground>

0 comments on commit c088cc8

Please sign in to comment.