Skip to content

Commit 9932b3a

Browse files
committed
feat(two-points): ✨更新167解题代码
1 parent 7f6e84c commit 9932b3a

File tree

3 files changed

+53
-33
lines changed

3 files changed

+53
-33
lines changed

Two-Points/141/solution2.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
* 快慢指针
1010
*
1111
*
12-
* 97.17%
13-
* 20.77%
12+
* 98.59%
13+
* 69.73%
1414
*
1515
*/
1616
const hasCycle = head => {

Two-Points/167/solution1.js

+31-29
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,33 @@
1-
/**
2-
* https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
3-
*
4-
* 167. 两数之和 II - 输入有序数组
5-
*
6-
* Easy
7-
*
8-
* 91.86%
9-
* 57.10%
10-
*/
11-
const twoSum = (numbers, target) => {
12-
const max = numbers.length
13-
let start = 0
14-
let end = max - 1
1+
/**
2+
* https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
3+
*
4+
* 167. 两数之和 II - 输入有序数组
5+
*
6+
* Easy
7+
*
8+
* 91.86%
9+
* 57.10%
10+
*/
11+
const twoSum = (numbers, target) => {
12+
const max = numbers.length
13+
let start = 0
14+
let end = max - 1
1515

16-
while (start < end) {
17-
const rest = target - numbers[end]
18-
if (rest < numbers[start]) {
19-
end--
20-
continue
21-
}
22-
if (rest > numbers[start]) {
23-
start++
24-
continue
25-
}
26-
if (rest === numbers[start]) {
27-
return [start + 1, end + 1]
28-
}
16+
while (start < end) {
17+
const sum = numbers[start] + numbers[end]
18+
19+
if (sum === target) {
20+
return [start + 1, end + 1]
21+
}
22+
23+
if (sum > target) {
24+
end--
25+
continue
26+
}
27+
28+
if (sum < target) {
29+
start++
30+
continue
2931
}
30-
return []
31-
}
32+
}
33+
}

Two-Points/readme.md

+20-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,24 @@
22

33
### 一、前言
44

5-
&emsp;&emsp;
5+
&emsp;&emsp;一般情况下,遍历数组(或者字符串)操作,都是采用单指针从前往后或者从后往前依次访问数组(或者字符串)中的元素。
66

7-
### 二、
7+
- 找到两个数使得它们相加之和等于目标数,采用单指针处理,需要嵌套循环;
8+
- 翻转数组,采用单指针处理,需要额外空间;
9+
10+
&emsp;&emsp;这种情况下就需要利用双指针技巧:
11+
12+
- 先对采用数组进行排序预处理,采用前后指针向中间遍历,遍历的时间复杂度为 O(n),整体处理的事件复杂度主要取决于排序,通常为 O(nlogn);
13+
- 一个指针负责遍历,一个指针负责交换元素,从而使得空间复杂度为 O(1);
14+
15+
&emsp;&emsp;下面通过实际的题目感受一下双指针的威力:
16+
17+
### 二、167. 两数之和 II - 输入有序数组
18+
19+
> 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
20+
21+
&emsp;&emsp;这道题目采用单指针的做法只能通过嵌套循环不断的计算两数之和,时间复杂度 O(n^2)。
22+
23+
&emsp;&emsp;恰巧本题中的数组已经是有序数组,那么直接创建前后指针:
24+
25+
-

0 commit comments

Comments
 (0)