第二次刷题
这次的题目比第一次更简单欸
PO一发题目:
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解题思路
水题想来也不用多说呢,这道题使用简单的O(n)算法就能通过
从数列的两端向内遍历,当numbers[i]+numbers[j]大于目标值时,要减小其中的大值,小于目标值时要增大其中的小值。当等于目标值的时候就可以返回啦。
放代码:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> result;
int j = numbers.size() - 1, i = 0;
while(i < j) {
if(numbers[i]+numbers[j]>target) j--;
else if(numbers[i]+numbers[j]<target) i++;
else {
result.push_back(i+1); result.push_back(j+1); break;
}
}
return result;
}
};