Skip to content

Commit ae3fc9f

Browse files
authored
docs: add a description of the solution to lcof problem: No.57 (doocs#711)
面试题57. 和为s的两个数字
1 parent 6a597fe commit ae3fc9f

File tree

1 file changed

+36
-2
lines changed
  • lcof/面试题57. 和为s的两个数字

1 file changed

+36
-2
lines changed

lcof/面试题57. 和为s的两个数字/README.md

+36-2
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,43 @@
2525

2626
## 解法
2727

28-
哈希表或双指针实现。时间复杂度均为 `O(n)`
28+
**哈希表**
2929

30-
哈希表空间复杂度 `O(n)`,双指针则是 `O(1)`
30+
遍历数组,查看哈希表中是否存在对应的差值(`target` - 遍历元素):
31+
- 存在,即 `return` 返回。
32+
- 不存在,记录元素,继续遍历。
33+
34+
*复杂度*
35+
36+
- 时间 ***O(N)***
37+
- 空间 ***O(N)***
38+
39+
**双指针**
40+
41+
1. 声明头尾指针(数组的左右两端)。
42+
2. 将头尾指针所指向的元素相加,与 `target` 比较:
43+
- 大于:尾指针前移。
44+
- 小于:头指针后移。
45+
- 等于:返回两个元素即可。
46+
3. 重复步骤 2,直到等于为止。
47+
48+
> 因为数组是有序的,指针变动对值的影响可预测。
49+
50+
*复杂度*
51+
52+
- 时间 ***O(N)***
53+
- 空间 ***O(1)***
54+
55+
```txt
56+
TWO-SUM(A,t)
57+
l = 0
58+
r = A.length - 1
59+
while A[l] + A[r] != t
60+
if A[l] + A[r] < t
61+
l = l + 1
62+
else r = r - 1
63+
return [A[l], A[r]]
64+
```
3165

3266
<!-- tabs:start -->
3367

0 commit comments

Comments
 (0)