File tree Expand file tree Collapse file tree 1 file changed +46
-2
lines changed
0167-Two-Sum-II-Input-array-is-sorted/Article Expand file tree Collapse file tree 1 file changed +46
-2
lines changed Original file line number Diff line number Diff line change 40
40
![ ] ( ../Animation/Animation.gif )
41
41
42
42
### 代码实现
43
-
44
- ```
43
+ #### C++
44
+ ``` c++
45
45
// 对撞指针
46
46
// 时间复杂度: O(n)
47
47
// 空间复杂度: O(1)
@@ -63,6 +63,50 @@ public:
63
63
64
64
65
65
```
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
+
66
110
67
111
68
112
You can’t perform that action at this time.
0 commit comments