[LeetCode] 167.Two Sum II - Input array is sorted
- 题目描述
- 解题思路
- 实验代码
题目描述
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解题思路
这道题看似很复杂,但要注意给定的vector中已经排好了序,所以使得问题简单化了,因为排序好了,所以两个数的和的大小情况就很容易判断了,根据大小情况作出相应的处理,具体见代码。
实验代码
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int m = 0, n = numbers.size()-1, k = numbers.size();
for (int i = 0; i < k; i++) {
if (m == n) break;
if (numbers[m] + numbers[n] == target) {
vector<int> v{m+1, n+1};
return v;
} else if (numbers[m] + numbers[n] > target) n--;
else m++;
}
}
};