Skip to content

Commit b665851

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题57. 和为s的两个数字
1 parent b586353 commit b665851

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# [面试题57. 和为s的两个数字](https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/)
2+
3+
## 题目描述
4+
输入一个递增排序的数组和一个数字 s,在数组中查找两个数,使得它们的和正好是 s。如果有多对数字的和等于 s,则输出任意一对即可。
5+
6+
**示例 1:**
7+
8+
```
9+
输入:nums = [2,7,11,15], target = 9
10+
输出:[2,7] 或者 [7,2]
11+
```
12+
13+
**示例 2:**
14+
15+
```
16+
输入:nums = [10,26,30,31,47,60], target = 40
17+
输出:[10,30] 或者 [30,10]
18+
```
19+
20+
**限制:**
21+
22+
- `1 <= nums.length <= 10^5`
23+
- `1 <= nums[i] <= 10^6`
24+
25+
## 解法
26+
### Python3
27+
```python
28+
class Solution:
29+
def twoSum(self, nums: List[int], target: int) -> List[int]:
30+
p, q = 0, len(nums) - 1
31+
while p < q:
32+
s = nums[p] + nums[q]
33+
if s == target:
34+
return [nums[p], nums[q]]
35+
if s < target:
36+
p += 1
37+
else:
38+
q -= 1
39+
40+
```
41+
42+
### Java
43+
```java
44+
class Solution {
45+
public int[] twoSum(int[] nums, int target) {
46+
int p = 0, q = nums.length - 1;
47+
while (p < q) {
48+
int s = nums[p] + nums[q];
49+
if (s == target) {
50+
return new int[] {nums[p], nums[q]};
51+
}
52+
if (s < target) {
53+
++p;
54+
} else {
55+
--q;
56+
}
57+
}
58+
return new int[]{0};
59+
}
60+
}
61+
```
62+
63+
### ...
64+
```
65+
66+
```
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int[] twoSum(int[] nums, int target) {
3+
int p = 0, q = nums.length - 1;
4+
while (p < q) {
5+
int s = nums[p] + nums[q];
6+
if (s == target) {
7+
return new int[] {nums[p], nums[q]};
8+
}
9+
if (s < target) {
10+
++p;
11+
} else {
12+
--q;
13+
}
14+
}
15+
return new int[]{0};
16+
}
17+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def twoSum(self, nums: List[int], target: int) -> List[int]:
3+
p, q = 0, len(nums) - 1
4+
while p < q:
5+
s = nums[p] + nums[q]
6+
if s == target:
7+
return [nums[p], nums[q]]
8+
if s < target:
9+
p += 1
10+
else:
11+
q -= 1

0 commit comments

Comments
 (0)