Skip to content

Commit d7cc4b6

Browse files
committed
Simplify twoSum logic by using (n) instead of the (target - n) as the dictionary key.
1 parent e1f32e0 commit d7cc4b6

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

Two-Sum Problem/Solution 1/2Sum.playground/Contents.swift

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,23 @@
44
print("Hello, Swift 4!")
55
#endif
66

7-
func twoSum(_ numbers: [Int], target: Int) -> (Int, Int)? {
8-
var dict: [Int: Int] = [:]
9-
10-
for (index, number) in numbers.enumerated() {
11-
if let otherIndex = dict[number] {
12-
return (index, otherIndex)
13-
} else {
14-
dict[target - number] = index
7+
func twoSum(_ nums: [Int], target: Int) -> (Int, Int)? {
8+
var dict = [Int: Int]()
9+
10+
for (currentIndex, n) in nums.enumerated() {
11+
let complement = target - n
12+
13+
if let complementIndex = dict[complement] {
14+
return (complementIndex, currentIndex)
15+
}
16+
17+
dict[n] = currentIndex
1518
}
16-
}
17-
18-
return nil
19+
20+
return nil
1921
}
2022

21-
let numbers = [3, 2, 4]
23+
let numbers = [3, 2, 8, 4]
2224
let target = 6
2325

24-
twoSum(numbers, target: target) // expected output: indices 2 and 1
26+
twoSum(numbers, target: target) // expected output: indices 1 and 3

0 commit comments

Comments
 (0)