Two Sum - Input array is sorted
思路:双循环
class Solution {
public:
/*
* @param nums an array of Integer
* @param target = nums[index1] + nums[index2]
* @return [index1 + 1, index2 + 1] (index1 < index2)
*/
vector<int> twoSum(vector<int> &nums, int target) {
// write your code here
int j = nums.size() - 1;
vector<int> answer;
for (int i =0; i <= j; i++) {
for (int k = i+1; k <= j; k++) {
if (nums[i] + nums[k] == target) {
answer.push_back(i + 1);
answer.push_back(k + 1);
return answer;
}
}
}
}
};
方法二;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size() - 1;
while (l < r) {
int sum = numbers[l] + numbers[r];
if (sum == target)
return {l + 1, r + 1};
else if (sum < target)
++l;
--r;
}
return {};
}
};