Created
September 9, 2019 18:34
-
-
Save PaulWoodIII/378b9e768e4420e32a0b03c82d354a08 to your computer and use it in GitHub Desktop.
twoSum Leetcode question 1 with Swift Generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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