Skip to content

Commit f43c086

Browse files
authored
Merge pull request #109 from ztianming/patch-3
Update 0167-Two-Sum-II-Input-array-is-sorted.md
2 parents 20bb4de + a86c0a0 commit f43c086

File tree

1 file changed

+64
-13
lines changed

1 file changed

+64
-13
lines changed

0167-Two-Sum-II-Input-array-is-sorted/Article/0167-Two-Sum-II-Input-array-is-sorted.md

+64-13
Original file line numberDiff line numberDiff line change
@@ -40,29 +40,80 @@
4040
![](../Animation/Animation.gif)
4141

4242
### 代码实现
43-
44-
```
43+
#### C++
44+
```c++
4545
// 对撞指针
4646
// 时间复杂度: O(n)
4747
// 空间复杂度: O(1)
4848
class Solution {
4949
public:
5050
vector<int> twoSum(vector<int>& numbers, int target) {
51-
int l = 0, r = numbers.size() - 1;
52-
while(l < r){
53-
if(numbers[l] + numbers[r] == target){
54-
int res[2] = {l+1, r+1};
55-
return vector<int>(res, res+2);
51+
int n = numbers.size();
52+
int left = 0;
53+
int right = n-1;
54+
while(left <= right)
55+
{
56+
if(numbers[left] + numbers[right] == target)
57+
{
58+
return {left + 1, right + 1};
59+
}
60+
else if (numbers[left] + numbers[right] > target)
61+
{
62+
right--;
63+
}
64+
else
65+
{
66+
left++;
5667
}
57-
else if(numbers[l] + numbers[r] < target)
58-
l ++;
59-
else // numbers[l] + numbers[r] > target
60-
r --;
6168
}
69+
return {-1, -1};
6270
}
63-
64-
71+
};
6572
```
73+
#### Java
74+
```java
75+
class Solution {
76+
public int[] twoSum(int[] numbers, int target) {
77+
int n = numbers.length;
78+
int left = 0;
79+
int right = n-1;
80+
while(left <= right)
81+
{
82+
if(numbers[left] + numbers[right] == target)
83+
{
84+
return new int[]{left + 1, right + 1};
85+
}
86+
else if (numbers[left] + numbers[right] > target)
87+
{
88+
right--;
89+
}
90+
else
91+
{
92+
left++;
93+
}
94+
}
95+
96+
return new int[]{-1, -1};
97+
}
98+
}
99+
```
100+
#### Python
101+
```python
102+
class Solution(object):
103+
def twoSum(self, numbers, target):
104+
n = len(numbers)
105+
left,right = 0, n-1
106+
while left <= right:
107+
if numbers[left]+numbers[right] == target:
108+
return [left+1, right+1]
109+
elif numbers[left]+numbers[right] > target:
110+
right -=1
111+
else:
112+
left +=1
113+
114+
return [-1, -1]
115+
```
116+
66117

67118

68119

0 commit comments

Comments
 (0)