Skip to content

Commit 5c1dcc1

Browse files
committed
Add two sum problem.
1 parent ec096a7 commit 5c1dcc1

File tree

4 files changed

+55
-1
lines changed

4 files changed

+55
-1
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.DS_Store

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1-
# Leetcode
1+
# Leetcode
2+
3+
### 📖 [Top 100 Interview Questions](https://leetcode.com/problemset/top-interview-questions/) 1/145 Solved
4+
5+
1. [Two Sum](<Top 100 Interview Questions/Two Sum>)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [Two Sum](https://leetcode.com/problems/two-sum/)
2+
3+
Given an array of integers `nums` and an integer `target`, return *indices of the two numbers such that they add up to `target`*.
4+
5+
You may assume that each input would have **exactly one solution**, and you may not use the same element twice.
6+
7+
You can return the answer in any order.
8+
9+
##### Example 1:
10+
11+
```
12+
Input: nums = [2,7,11,15], target = 9
13+
Output: [0,1]
14+
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
15+
```
16+
17+
##### Example 2:
18+
19+
```
20+
Input: nums = [3,2,4], target = 6
21+
Output: [1,2]
22+
```
23+
24+
##### Example 3:
25+
26+
```
27+
Input: nums = [3,3], target = 6
28+
Output: [0,1]
29+
```
30+
31+
##### Constraints:
32+
33+
* `2 <= nums.length <= 10³`
34+
* `-10⁹ <= nums[i] <= 10⁹`
35+
* `-10⁹ <= target <= 10⁹`
36+
* **Only one valid answer exists**.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
final class Solution {
2+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
3+
var map: [Int: Int] = [:]
4+
for (index, value) in nums.enumerated() {
5+
let remainder = target - value
6+
if let rightIndex = map[remainder] {
7+
return [index, rightIndex]
8+
}
9+
map[value] = index
10+
}
11+
return []
12+
}
13+
}

0 commit comments

Comments
 (0)