Skip to content

Commit 129f9a8

Browse files
authored
Update 0167-Two-Sum-II-Input-array-is-sorted.md
添加Java、Python代码实现
1 parent 3daa187 commit 129f9a8

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

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

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@
4040
![](../Animation/Animation.gif)
4141

4242
### 代码实现
43-
44-
```
43+
#### C++
44+
```c++
4545
// 对撞指针
4646
// 时间复杂度: O(n)
4747
// 空间复杂度: O(1)
@@ -63,6 +63,50 @@ public:
6363

6464

6565
```
66+
#### Java
67+
```java
68+
class Solution {
69+
public int[] twoSum(int[] numbers, int target) {
70+
int n = numbers.length;
71+
int left = 0;
72+
int right = n-1;
73+
while(left <= right)
74+
{
75+
if(numbers[left] + numbers[right] == target)
76+
{
77+
return new int[]{left + 1, right + 1};
78+
}
79+
else if (numbers[left] + numbers[right] > target)
80+
{
81+
right--;
82+
}
83+
else
84+
{
85+
left++;
86+
}
87+
}
88+
89+
return new int[]{-1, -1};
90+
}
91+
}
92+
```
93+
#### Python
94+
```python
95+
class Solution(object):
96+
def twoSum(self, numbers, target):
97+
n = len(numbers)
98+
left,right = 0, n-1
99+
while left <= right:
100+
if numbers[left]+numbers[right] == target:
101+
return [left+1, right+1]
102+
elif numbers[left]+numbers[right] > target:
103+
right -=1
104+
else:
105+
left +=1
106+
107+
return [-1, -1]
108+
```
109+
66110

67111

68112

0 commit comments

Comments
 (0)