---
# System prepended metadata

title: 0167. Two Sum II - Input Array Is Sorted
tags: [Leetcode, Two Pointers, Binary Search]

---

# 0167. Two Sum II - Input Array Is Sorted
###### tags: `Leetcode` `Binary Search` `Two Pointers` 
Link: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
## 思路
### Two Pointers $O(N)$ $O(1)$
### Binary Search $O(NlogN)$ $O(1)$
## Code
### Two Pointers
```java=
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int l = 0;
        int r = numbers.length-1;
        while(numbers[l]+numbers[r]!=target){
            if(numbers[l]+numbers[r]<target){
                l++;
            }
            else{
                r--;
            }
        }
        return new int[]{l+1, r+1};
    }
}
```
### Binary Search
```java=
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        for(int i = 0;i < numbers.length;i++){
            int start = i+1;
            int end = numbers.length;
            while(start<end){
                int mid = start+(end-start)/2;
                if(numbers[mid] < target-numbers[i]){
                    start = mid+1;
                }
                else{
                    end = mid;
                }
            }
            if(start!=numbers.length && numbers[start]+numbers[i]==target){
                return new int[]{i+1, start+1};
            }
        }
        return new int[]{0};
    }
}
```