You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
7
9
@@ -16,15 +18,18 @@ return [0, 1].
16
18
```
17
19
18
20
## Solution
21
+
19
22
The easiest solution to come up with is Brute Force. We could write two for-loops to traverse every element, and find the target numbers that meet the requirement. However, the time complexity of this solution is O(N^2), while the space complexity is O(1). Apparently, we need to find a way to optimize this solution since the time complexity is too high. What we could do is to record the numbers we have traversed and the relevant index with a Map. Whenever we meet a new number during traversal, we go back to the Map and check whether the `diff` between this number and the target number appeared before. If it did, the problem has been solved and there's no need to continue.
20
23
21
24
## Key Points
22
-
- Find the difference instead of the sum
23
-
- Connect every number with its index through the help of Map
24
-
- Less time by more space. Reduce the time complexity from O(N) to O(1)
25
25
26
-
## Code
27
-
- Support Language: JS
26
+
- Find the difference instead of the sum
27
+
- Connect every number with its index through the help of Map
28
+
- Less time by more space. Reduce the time complexity from O(N) to O(1)
29
+
30
+
## Code
31
+
32
+
- Support Language: JS
28
33
29
34
```js
30
35
/**
@@ -33,18 +38,18 @@ The easiest solution to come up with is Brute Force. We could write two for-loop
0 commit comments