Skip to content

Instantly share code, notes, and snippets.

@thieunguyencrystal
Created March 17, 2019 11:57
Show Gist options
  • Save thieunguyencrystal/dfc8607bbc47db6e0f1dca537bbc528f to your computer and use it in GitHub Desktop.
Save thieunguyencrystal/dfc8607bbc47db6e0f1dca537bbc528f to your computer and use it in GitHub Desktop.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
/*
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
*/
import UIKit
var array = [10, 15, 3, 7]
let k = 17
let sortedArray = array.sorted()
let count = sortedArray.count
var low = 0
var high = count - 1
while (low < high) {
let sum = sortedArray[low] + sortedArray[high]
if sum == k {
print("\(sortedArray[low]) + \(sortedArray[high])")
high = high - 1
low = low + 1
} else if sum > k {
high = high - 1
} else {
low = low + 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment