Skip to content

Instantly share code, notes, and snippets.

@isisnaomi
Last active October 16, 2019 21:08
Show Gist options
  • Save isisnaomi/2c3596c3be31892877965af9135956eb to your computer and use it in GitHub Desktop.
Save isisnaomi/2c3596c3be31892877965af9135956eb to your computer and use it in GitHub Desktop.
Two Sum
/**
* TwoSum
* Write a function that takes a list and outputs alist of numbers
* belonging to the list that can be summed up to the first element of the list.
*
* Test Cases
* > twoSum [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]
* 6, 11, 10, 7, 15, 2
*
* > twoSum [7, 6, 4, 1, 7, -2, 3, 12]
* 6, 1, 4, 3
*/
func twoSum(_ array: [Int]) -> [Int] {
var result: [Int] = []
var complement: [Int] = []
let firstElement = array[0]
for element in array {
if complement.contains(element) {
result.append(firstElement - element)
result.append(element)
} else {
complement.append(firstElement - element)
}
}
return result
}
func coolTwoSum(_ array: [Int]) -> [Int] {
let firstElement = array[0]
return array.filter { array.contains(firstElement - $0) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment