Skip to content

Instantly share code, notes, and snippets.

@PaulWoodIII
Created September 9, 2019 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulWoodIII/378b9e768e4420e32a0b03c82d354a08 to your computer and use it in GitHub Desktop.
Save PaulWoodIII/378b9e768e4420e32a0b03c82d354a08 to your computer and use it in GitHub Desktop.
twoSum Leetcode question 1 with Swift Generics
import Foundation
/*
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
*/
extension Sequence where Element: AdditiveArithmetic, Element: Hashable {
func summedPair(_ search: Element) -> (Int,Int)? {
var compliments = [Element:Int]()
for (idx, element) in self.enumerated() {
let comp: Element = search - element
if let found = compliments[element] {
return (found, idx)
} else {
compliments[comp] = idx
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment