Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit47cead7

Browse files
committed
docs: update 1-two-sum.md to match leetcoder.net format
1 parent2a56032 commit47cead7

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 objecttobe 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()` methodtofind 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+
classSolution:
78+
deftwoSum(self,nums: List[int],target:int) -> List[int]:
79+
num_index_list= [(num, i)for i, numinenumerate(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=newMap()
66-
67-
for (let i=0; i<nums.length; i++) {
68-
numToIndex.set(nums[i], i)
69-
}
70-
```
113+
```javascript
114+
let numToIndex=newMap()
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=newMap()
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-
### Solution1: Two pointers
92-
```java
93-
// Welcome to create a PR to complete the code, thanks!
94-
```
95138

96-
### Solution2: UsingMap
97139
```java
98140
classSolution {
99141
publicint[]twoSum(int[]nums,inttarget) {
100142
var numToIndex=newHashMap<Integer,Integer>();
101-
143+
102144
for (var i=0; i< nums.length; i++) {
103145
if (numToIndex.containsKey(target- nums[i])) {
104146
returnnewint[]{numToIndex.get(target- nums[i]), i};
@@ -113,37 +155,12 @@ class Solution {
113155
```
114156

115157
##Python
116-
### Solution1: 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-
### Solution2: UsingMap
142159
```python
143160
classSolution:
144161
deftwoSum(self,nums: List[int],target:int) -> List[int]:
145162
num_to_index= {}
146-
163+
147164
for i, numinenumerate(nums):
148165
if target- numin num_to_index:
149166
return [num_to_index[target- num], i]
@@ -152,18 +169,13 @@ class Solution:
152169
```
153170

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

160-
### Solution2: UsingMap
161173
```cpp
162174
classSolution {
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-
### Solution1: Two pointers
182-
```javascript
183-
// Welcome to create a PR to complete the code, thanks!
184-
```
185193

186-
### Solution2: UsingMap
187194
```javascript
188195
vartwoSum=function (nums,target) {
189196
let numToIndex=newMap()
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-
### Solution1: Two pointers
203-
```c#
204-
// Welcome to create a PR to complete the code, thanks!
205-
```
206209

207-
### Solution2: UsingMap
208210
```c#
209211
publicclassSolution {
210212
publicint[]TwoSum(int[]nums,inttarget) {
211213
varnumToIndex=newDictionary<int,int>();
212-
214+
213215
for (inti=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-
### Solution1: Two pointers
228-
```go
229-
// Welcome to create a PR to complete the code, thanks!
230-
```
231229

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

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

255-
### Solution2: UsingMap
256248
```ruby
257249
deftwo_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+
classSolution:
283+
deftwoSum(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)

[8]ページ先頭

©2009-2025 Movatter.jp