未验证 提交 f43c0860 编写于 作者: 程序员吴师兄 提交者: GitHub

Merge pull request #109 from ztianming/patch-3

Update 0167-Two-Sum-II-Input-array-is-sorted.md
...@@ -40,30 +40,81 @@ ...@@ -40,30 +40,81 @@
![](../Animation/Animation.gif) ![](../Animation/Animation.gif)
### 代码实现 ### 代码实现
#### C++
``` ```c++
// 对撞指针 // 对撞指针
// 时间复杂度: O(n) // 时间复杂度: O(n)
// 空间复杂度: O(1) // 空间复杂度: O(1)
class Solution { class Solution {
public: public:
vector<int> twoSum(vector<int>& numbers, int target) { vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size() - 1; int n = numbers.size();
while(l < r){ int left = 0;
if(numbers[l] + numbers[r] == target){ int right = n-1;
int res[2] = {l+1, r+1}; while(left <= right)
return vector<int>(res, res+2); {
if(numbers[left] + numbers[right] == target)
{
return {left + 1, right + 1};
} }
else if(numbers[l] + numbers[r] < target) else if (numbers[left] + numbers[right] > target)
l ++; {
else // numbers[l] + numbers[r] > target right--;
r --; }
else
{
left++;
}
}
return {-1, -1};
}
};
```
#### Java
```java
class Solution {
public int[] twoSum(int[] numbers, int target) {
int n = numbers.length;
int left = 0;
int right = n-1;
while(left <= right)
{
if(numbers[left] + numbers[right] == target)
{
return new int[]{left + 1, right + 1};
}
else if (numbers[left] + numbers[right] > target)
{
right--;
}
else
{
left++;
} }
} }
return new int[]{-1, -1};
}
}
```
#### Python
```python
class Solution(object):
def twoSum(self, numbers, target):
n = len(numbers)
left,right = 0, n-1
while left <= right:
if numbers[left]+numbers[right] == target:
return [left+1, right+1]
elif numbers[left]+numbers[right] > target:
right -=1
else:
left +=1
return [-1, -1]
``` ```
![](../../Pictures/qrcode.jpg) ![](../../Pictures/qrcode.jpg)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册