Skip to content

Commit 47cead7

Browse files
committed
docs: update 1-two-sum.md to match leetcoder.net format
1 parent 2a56032 commit 47cead7

File tree

1 file changed

+141
-102
lines changed

1 file changed

+141
-102
lines changed

en/1-1000/1-two-sum.md

Lines changed: 141 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -1,104 +1,146 @@
1-
# 1. Two Sum - Best Practices of LeetCode Solutions
2-
LeetCode link: [1. Two Sum](https://leetcode.com/problems/two-sum), difficulty: **Easy**
1+
Original link: [leetcoder.net - LeetCoder: Fucking Good LeetCode Solutions](https://leetcoder.net/en/leetcode/1-two-sum)
2+
3+
# 1. Two Sum - LeetCoder: Fucking Good LeetCode Solutions
4+
5+
LeetCode link: [1. Two Sum](https://leetcode.com/problems/two-sum), Difficulty: **Easy**.
36

47
## LeetCode description of "1. Two Sum"
8+
59
Given an array of integers `nums` and an integer `target`, return *indices of the two numbers such that they add up to `target`*.
610

711
You may assume that each input would have ***exactly* one solution**, and you may not use the same element twice.
812

913
You can return the answer in any order.
1014

1115
### [Example 1]
16+
1217
**Input**: `nums = [2,7,11,15], target = 9`
1318

1419
**Output**: `[0,1]`
1520

16-
**Explanation**`Because nums[0] + nums[1] == 9, we return [0, 1].`
21+
**Explanation**: Because nums[0] + nums[1] == 9, we return [0, 1].
1722

1823
### [Example 2]
24+
1925
**Input**: `nums = [3,2,4], target = 6`
2026

2127
**Output**: `[1,2]`
2228

29+
### [Example 3]
30+
31+
**Input**: `nums = [3,3], target = 6`
32+
33+
**Output**: `[0,1]`
34+
2335
### [Constraints]
36+
2437
- `2 <= nums.length <= 10^4`
2538
- `-10^9 <= nums[i] <= 10^9`
2639
- `-10^9 <= target <= 10^9`
2740
- **Only one valid answer exists.**
2841

2942
### [Hints]
30-
<details>
31-
<summary>Hint 1</summary>
43+
44+
Hint 1
45+
3246
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations.
33-
</details>
3447

35-
<details>
36-
<summary>Hint 2</summary>
48+
---
49+
50+
Hint 2
51+
3752
So, if we fix one of the numbers, say `x`, we have to scan the entire array to find the next number `y` which is `value - x` where value is the input parameter. Can we change our array somehow so that this search becomes faster?
38-
</details>
3953

40-
<details>
41-
<summary>Hint 3</summary>
54+
---
55+
56+
Hint 3
57+
4258
The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
43-
</details>
4459

45-
## Intuition
60+
## Intuition 1
61+
4662
1. The time complexity of the brute force solution is `O(n**2)`. To improve efficiency, you can sort the array, and then use **two pointers**, one pointing to the head of the array and the other pointing to the tail of the array, and decide `left += 1` or `right -= 1` according to the comparison of `sum` and `target`.
4763

4864
2. After sorting an array of numbers, if you want to know the original `index` corresponding to a certain value, there are two solutions:
4965

50-
- Solution 1: Use `index()` method to find it.
51-
- Solution 2: Bring the `index` when sorting, that is, the object to be sorted is an array of tuples of `(num, index)`.
66+
- Solution 1: Bring the `index` when sorting, that is, the object to be sorted is an array of tuples of `(num, index)`. This technique **must be mastered**, as it will be used in many questions.
67+
- Solution 2: Use `index()` method to find it. I have discussed this in another solution.
5268

53-
### Complexity
54-
* Time: `O(N * log N)`.
55-
* Space: `O(N)`.
69+
## Complexity
70+
71+
- Time complexity: `O(N * log N)`.
72+
- Space complexity: `O(N)`.
73+
74+
## Python
75+
76+
```python
77+
class Solution:
78+
def twoSum(self, nums: List[int], target: int) -> List[int]:
79+
num_index_list = [(num, i) for i, num in enumerate(nums)]
80+
num_index_list.sort()
81+
82+
left = 0
83+
right = len(nums) - 1
84+
85+
while left < right:
86+
sum_ = num_index_list[left][0] + num_index_list[right][0]
87+
88+
if sum_ == target:
89+
return [num_index_list[left][1], num_index_list[right][1]]
90+
91+
if sum_ < target:
92+
left += 1
93+
continue
94+
95+
right -= 1
96+
```
97+
98+
## Other languages
99+
100+
```java
101+
// Welcome to create a PR to complete the code of this language, thanks!
102+
```
103+
104+
## Intuition 2
56105

57-
## Solution 2: Use Map (also should master)
58106
1. In `Map`, `key` is `num`, and `value` is array `index`.
59107
2. Traverse the array, if `target - num` is in `Map`, return it. Otherwise, add `num` to `Map`.
60108

61-
### Steps
109+
## Steps
110+
62111
1. In `Map`, `key` is `num`, and `value` is array `index`.
63112

64-
```javascript
65-
let numToIndex = new Map()
66-
67-
for (let i = 0; i < nums.length; i++) {
68-
numToIndex.set(nums[i], i)
69-
}
70-
```
113+
```javascript
114+
let numToIndex = new Map()
115+
for (let i = 0; i < nums.length; i++) {
116+
numToIndex.set(nums[i], i)
117+
}
118+
```
71119

72120
2. Traverse the array, if `target - num` is in `Map`, return it. Otherwise, add `num` to `Map`.
73121

74-
```javascript
75-
let numToIndex = new Map()
76-
77-
for (let i = 0; i < nums.length; i++) {
78-
if (numToIndex.has(target - nums[i])) { // 1
79-
return [numToIndex.get(target - nums[i]), i] // 2
80-
}
81-
82-
numToIndex.set(nums[i], i)
83-
}
84-
```
122+
```javascript
123+
let numToIndex = new Map()
124+
for (let i = 0; i < nums.length; i++) {
125+
if (numToIndex.has(target - nums[i])) { // 1
126+
return [numToIndex.get(target - nums[i]), i] // 2
127+
}
128+
numToIndex.set(nums[i], i)
129+
}
130+
```
131+
132+
## Complexity
85133

86-
### Complexity
87-
* Time: `O(n)`.
88-
* Space: `O(n)`.
134+
- Time complexity: `O(N)`.
135+
- Space complexity: `O(N)`.
89136

90137
## Java
91-
### Solution 1: Two pointers
92-
```java
93-
// Welcome to create a PR to complete the code, thanks!
94-
```
95138

96-
### Solution 2: Using Map
97139
```java
98140
class Solution {
99141
public int[] twoSum(int[] nums, int target) {
100142
var numToIndex = new HashMap<Integer, Integer>();
101-
143+
102144
for (var i = 0; i < nums.length; i++) {
103145
if (numToIndex.containsKey(target - nums[i])) {
104146
return new int[]{numToIndex.get(target - nums[i]), i};
@@ -113,37 +155,12 @@ class Solution {
113155
```
114156

115157
## Python
116-
### Solution 1: Two pointers
117-
```python
118-
class Solution:
119-
def twoSum(self, nums: List[int], target: int) -> List[int]:
120-
original_nums = nums.copy()
121-
nums.sort()
122-
123-
left = 0
124-
right = len(nums) - 1
125158

126-
while left < right:
127-
sum_ = nums[left] + nums[right]
128-
129-
if sum_ == target:
130-
break
131-
132-
if sum_ < target:
133-
left += 1
134-
continue
135-
136-
right -= 1
137-
138-
return [original_nums.index(nums[left]), len(nums) - 1 - original_nums[::-1].index(nums[right])]
139-
```
140-
141-
### Solution 2: Using Map
142159
```python
143160
class Solution:
144161
def twoSum(self, nums: List[int], target: int) -> List[int]:
145162
num_to_index = {}
146-
163+
147164
for i, num in enumerate(nums):
148165
if target - num in num_to_index:
149166
return [num_to_index[target - num], i]
@@ -152,18 +169,13 @@ class Solution:
152169
```
153170

154171
## C++
155-
### Solution 1: Two pointers
156-
```cpp
157-
// Welcome to create a PR to complete the code, thanks!
158-
```
159172

160-
### Solution 2: Using Map
161173
```cpp
162174
class Solution {
163175
public:
164176
vector<int> twoSum(vector<int>& nums, int target) {
165177
unordered_map<int, int> num_to_index;
166-
178+
167179
for (auto i = 0; i < nums.size(); i++) {
168180
if (num_to_index.contains(target - nums[i])) {
169181
return {num_to_index[target - nums[i]], i};
@@ -178,16 +190,11 @@ public:
178190
```
179191

180192
## JavaScript
181-
### Solution 1: Two pointers
182-
```javascript
183-
// Welcome to create a PR to complete the code, thanks!
184-
```
185193

186-
### Solution 2: Using Map
187194
```javascript
188195
var twoSum = function (nums, target) {
189196
let numToIndex = new Map()
190-
197+
191198
for (let i = 0; i < nums.length; i++) {
192199
if (numToIndex.has(target - nums[i])) {
193200
return [numToIndex.get(target - nums[i]), i]
@@ -199,17 +206,12 @@ var twoSum = function (nums, target) {
199206
```
200207

201208
## C#
202-
### Solution 1: Two pointers
203-
```c#
204-
// Welcome to create a PR to complete the code, thanks!
205-
```
206209

207-
### Solution 2: Using Map
208210
```c#
209211
public class Solution {
210212
public int[] TwoSum(int[] nums, int target) {
211213
var numToIndex = new Dictionary<int, int>();
212-
214+
213215
for (int i = 0; i < nums.Length; i++) {
214216
if (numToIndex.ContainsKey(target - nums[i])) {
215217
return [numToIndex[target - nums[i]], i];
@@ -224,12 +226,7 @@ public class Solution {
224226
```
225227

226228
## Go
227-
### Solution 1: Two pointers
228-
```go
229-
// Welcome to create a PR to complete the code, thanks!
230-
```
231229

232-
### Solution 2: Using Map
233230
```go
234231
func twoSum(nums []int, target int) []int {
235232
numToIndex := map[int]int{}
@@ -247,12 +244,7 @@ func twoSum(nums []int, target int) []int {
247244
```
248245

249246
## Ruby
250-
### Solution 1: Two pointers
251-
```ruby
252-
# Welcome to create a PR to complete the code, thanks!
253-
```
254247

255-
### Solution 2: Using Map
256248
```ruby
257249
def two_sum(nums, target)
258250
num_to_index = {}
@@ -267,7 +259,54 @@ def two_sum(nums, target)
267259
end
268260
```
269261

270-
## C, Kotlin, Swift, Rust or other languages
262+
## Other languages
263+
264+
```java
265+
// Welcome to create a PR to complete the code of this language, thanks!
271266
```
267+
268+
## Intuition 3
269+
270+
1. The time complexity of the brute force solution is `O(n^2)`. To improve efficiency, you can sort the array, and then use **two pointers**, one pointing to the head of the array and the other pointing to the tail of the array, and decide `left += 1` or `right -= 1` according to the comparison of `sum` and `target`.
271+
272+
2. After finding the two values which `sum` is `target`, you can use the `index()` method to find the `index` corresponding to the value.
273+
274+
## Complexity
275+
276+
- Time complexity: `O(N * log N)`.
277+
- Space complexity: `O(N)`.
278+
279+
## Python
280+
281+
```python
282+
class Solution:
283+
def twoSum(self, nums: List[int], target: int) -> List[int]:
284+
original_nums = nums.copy()
285+
nums.sort()
286+
287+
left = 0
288+
right = len(nums) - 1
289+
290+
while left < right:
291+
sum_ = nums[left] + nums[right]
292+
293+
if sum_ == target:
294+
break
295+
296+
if sum_ < target:
297+
left += 1
298+
continue
299+
300+
right -= 1
301+
302+
return [
303+
original_nums.index(nums[left]),
304+
len(nums) - 1 - original_nums[::-1].index(nums[right])
305+
]
306+
```
307+
308+
## Other languages
309+
310+
```java
272311
// Welcome to create a PR to complete the code of this language, thanks!
273312
```

0 commit comments

Comments
 (0)