Skip to content

Instantly share code, notes, and snippets.

@davidseek
Last active May 29, 2020 21:26
Show Gist options
  • Select an option

  • Save davidseek/10199bc3ba5712a0ae88d187b467a8b2 to your computer and use it in GitHub Desktop.

Select an option

Save davidseek/10199bc3ba5712a0ae88d187b467a8b2 to your computer and use it in GitHub Desktop.
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// Iterate through every element in numbers
for (i, number1) in numbers.enumerated() {
/**
For every iteration,
iterate through numbers,
where i does not equal j.
*/
for (j, number2) in numbers.enumerated() where i != j {
// Get the sum of number1 and number2
let sum = number1 + number2
// Check if sum equals the target
if sum == target {
// If so, return the indicies or numbers
return [i, j] // or [number1, number2]
}
}
}
/**
Return an empty array if unable to
find a pair that adds up to the target.
*/
return []
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment