File tree Expand file tree Collapse file tree 1 file changed +15
-13
lines changed
Two-Sum Problem/Solution 1/2Sum.playground Expand file tree Collapse file tree 1 file changed +15
-13
lines changed Original file line number Diff line number Diff line change 4
4
print ( " Hello, Swift 4! " )
5
5
#endif
6
6
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
15
18
}
16
- }
17
-
18
- return nil
19
+
20
+ return nil
19
21
}
20
22
21
- let numbers = [ 3 , 2 , 4 ]
23
+ let numbers = [ 3 , 2 , 8 , 4 ]
22
24
let target = 6
23
25
24
- twoSum ( numbers, target: target) // expected output: indices 2 and 1
26
+ twoSum ( numbers, target: target) // expected output: indices 1 and 3
You can’t perform that action at this time.
0 commit comments