Skip to content

Commit ab0efc7

Browse files
author
Yi Gu
committed
Update solution to Two Sum
1 parent 9ca65f9 commit ab0efc7

File tree

2 files changed

+10
-13
lines changed

2 files changed

+10
-13
lines changed

Array/TwoSum.swift

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,21 @@
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

88
class 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
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
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)|

0 commit comments

Comments
 (0)