Skip to content

Instantly share code, notes, and snippets.

@shanecowherd
Last active November 17, 2019 20:32
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 shanecowherd/d514df14812244b70689feb4e7ac1d78 to your computer and use it in GitHub Desktop.
Save shanecowherd/d514df14812244b70689feb4e7ac1d78 to your computer and use it in GitHub Desktop.
The typical two sum solution
// Create a dictionary with the key the index of each item in the array.
// The value is the difference between the array's value and the target.
// Now if we want to find the first solution that contains sum, just loop
// through the array and check the dictionary for other numbers who match the difference.
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dict = [Int:Int]()
for (i, val) in nums.enumerated() {
let differenceBetweenTwoNumbers = target-val
if let difference = hashTable[differenceBetweenTwoNumbers] {
return [difference, i]
}
dict[val] = i
}
return [0,0] //Should not hit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment