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 22 * Question Link: https://leetcode.com/problems/two-sum/
33 * Primary idea: Traverse the array and store target - nums[i] in a dict
44 *
5- * Time Complexity: O(n), Space Complexity: O(nC2 )
5+ * Time Complexity: O(n), Space Complexity: O(n )
66 */
77
88class TwoSum {
9- func twoSum( nums: [ Int ] , _ target: Int ) -> [ Int ] {
10- var res = [ Int] ( )
9+ func twoSum( _ nums: [ Int ] , _ target: Int ) -> [ Int ] {
1110 var dict = [ Int: Int] ( )
12-
11+
1312 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]
1715 }
18-
19- res. append ( lastIndex)
20- res. append ( i)
16+
17+ dict [ num] = i
2118 }
22-
23- return res
19+
20+ fatalError ( " No valid outputs " )
2421 }
2522}
Original file line number Diff line number Diff line change 4646[ 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)|
4747[ Move Zeroes] ( https://leetcode.com/problems/move-zeroes/ ) | [ Swift] ( ./Array/MoveZeroes.swift ) | Easy| O(n)| O(1)|
4848[ 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 )|
5050[ 3Sum] ( https://leetcode.com/problems/3sum/ ) | [ Swift] ( ./Array/ThreeSum.swift ) | Medium| O(n^2)| O(nC3)|
5151[ 3Sum Closest] ( https://leetcode.com/problems/3sum-closest/ ) | [ Swift] ( ./Array/ThreeSum.swift ) | Medium| O(n^2)| O(nC3)|
5252[ 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