---
# System prepended metadata

title: 'Leetcode [No. 167] Two Sum II - Input Array Is Sorted (MEDIUM) 解題心得'
tags: [leetcode]

---

# Leetcode [No. 167] Two Sum II - Input Array Is Sorted (MEDIUM) 解題心得

+ Solved on 2024/06/26 Neetcode 150 (Two Pointer)


## 題目

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

* 這題有規定只能用constant extra space !!!

## 思路
+ 這個解法就是利用已經sort過的特性，搭配two pointer 來秒殺這個問題

```c++=
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int left = 0, right = numbers.size()-1;
        while(left < right)
        {
            int sum = numbers[left] + numbers[right];
            if(sum == target)
            {
                return {left+1, right+1};
            }
            else if (sum < target)
            {
                left++;
            }
            else
            {
                right--;
            }
        }
        return {};
    }
};
```

### 解法分析
+ time complexity: O(n)


### 執行結果
![image](https://hackmd.io/_uploads/HJqCfjYLA.png)


