Skip to content

Commit 2695f42

Browse files
committed
Solution: Two Sum
1 parent d0eed34 commit 2695f42

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

two-sum/flynn.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
## Description
2+
3+
`key: num, value: index`를 저장할 hashmap을 선언합니다.
4+
5+
배열 `nums`의 첫번째 원소를 hashmap에 저장합니다. (`nums[0]: 0`)
6+
7+
배열 `nums`를 두번째 원소부터 조회하여 `target - nums[i]`가 hashmap에 존재하는지 판단합니다.
8+
9+
만약 `target - nums[i]`가 hashmap에 존재한다면 정답 배열을 반환하고, 그렇지 않다면 hashmap에 새로운 쌍을 추가합니다.
10+
11+
## Big-O
12+
13+
주어진 배열 `nums`의 크기 N에 대해,
14+
15+
Time complexity: `O(N)`
16+
17+
- 배열 `nums`를 순회하기 때문에 `O(N)`의 시간 복잡도를 가집니다.
18+
19+
Space complexity: `O(N)`
20+
21+
- hashmap의 크기가 배열 `nums`의 크기에 가깝게 커질 수 있으므로 `O(N)`의 공간복잡도를 가집니다.
22+
23+
---
24+
25+
```cpp
26+
class Solution {
27+
public:
28+
vector<int> twoSum(vector<int>& nums, int target) {
29+
unordered_map<int, int> past; // key: num value: index
30+
vector<int> res;
31+
32+
past.insert({nums[0], 0});
33+
34+
for (int i = 1; i < nums.size(); i++) {
35+
int remainder = target - nums[i];
36+
37+
if (past.find(remainder) != past.end()) {
38+
res.push_back(i);
39+
res.push_back(past[remainder]);
40+
break;
41+
} else {
42+
past.insert({nums[i], i});
43+
}
44+
}
45+
46+
return res;
47+
}
48+
};
49+
```

0 commit comments

Comments
 (0)