167. 两数之和 II - 输入有序数组
双指针法
特别easy的题,左右双指针遍历就行,时间复杂度 O ( n )
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> a; int n = numbers.size(); int left = 0, right = n - 1; while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) { a.push_back(left + 1); a.push_back(right + 1); break; } else if (sum > target) { right--; } else { left++; } } return a; } };
最开始想直接暴力过,优化还是超时。想着easy题都写不出来,想重开了。