File tree Expand file tree Collapse file tree 2 files changed +10
-13
lines changed Expand file tree Collapse file tree 2 files changed +10
-13
lines changed Original file line number Diff line number Diff line change 2
2
* Question Link: https://leetcode.com/problems/two-sum/
3
3
* Primary idea: Traverse the array and store target - nums[i] in a dict
4
4
*
5
- * Time Complexity: O(n), Space Complexity: O(nC2 )
5
+ * Time Complexity: O(n), Space Complexity: O(n )
6
6
*/
7
7
8
8
class TwoSum {
9
- func twoSum( nums: [ Int ] , _ target: Int ) -> [ Int ] {
10
- var res = [ Int] ( )
9
+ func twoSum( _ nums: [ Int ] , _ target: Int ) -> [ Int ] {
11
10
var dict = [ Int: Int] ( )
12
-
11
+
13
12
for (i, num) in nums. enumerated ( ) {
14
- guard let lastIndex = dict [ target - num] else {
15
- dict [ num] = i
16
- continue
13
+ if let lastIndex = dict [ target - num] {
14
+ return [ lastIndex, i]
17
15
}
18
-
19
- res. append ( lastIndex)
20
- res. append ( i)
16
+
17
+ dict [ num] = i
21
18
}
22
-
23
- return res
19
+
20
+ fatalError ( " No valid outputs " )
24
21
}
25
22
}
Original file line number Diff line number Diff line change 46
46
[ Remove Duplicates from Sorted Array II] ( https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ ) | [ Swift] ( ./Array/RemoveDuplicatesFromSortedArrayII.swift ) | Medium| O(n)| O(1)|
47
47
[ Move Zeroes] ( https://leetcode.com/problems/move-zeroes/ ) | [ Swift] ( ./Array/MoveZeroes.swift ) | Easy| O(n)| O(1)|
48
48
[ Remove Element] ( https://leetcode.com/problems/remove-element/ ) | [ Swift] ( ./Array/RemoveElement.swift ) | Easy| O(n)| O(1)|
49
- [ Two Sum] ( https://leetcode.com/problems/two-sum/ ) | [ Swift] ( ./Array/TwoSum.swift ) | Easy| O(n)| O(nC2 )|
49
+ [ Two Sum] ( https://leetcode.com/problems/two-sum/ ) | [ Swift] ( ./Array/TwoSum.swift ) | Easy| O(n)| O(n )|
50
50
[ 3Sum] ( https://leetcode.com/problems/3sum/ ) | [ Swift] ( ./Array/ThreeSum.swift ) | Medium| O(n^2)| O(nC3)|
51
51
[ 3Sum Closest] ( https://leetcode.com/problems/3sum-closest/ ) | [ Swift] ( ./Array/ThreeSum.swift ) | Medium| O(n^2)| O(nC3)|
52
52
[ 4Sum] ( https://leetcode.com/problems/4sum/ ) | [ Swift] ( ./Array/FourSum.swift ) | Medium| O(n^3)| O(nC4)|
You can’t perform that action at this time.
0 commit comments