Last active
November 17, 2019 20:32
-
-
Save shanecowherd/d514df14812244b70689feb4e7ac1d78 to your computer and use it in GitHub Desktop.
The typical two sum solution
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
// 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