思路
方法一:二分
遍历每个数字num,然后再在后面的数字中使用二分查找target-num。
复杂度分析
时间复杂度:O(nlogn)
空间复杂度:O(1)
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 int left, mid, right; 5 for(int i = 0; i < nums.size()-1; ++i) { 6 left = i+1; 7 right = nums.size()-1; 8 while(left <= right) { 9 mid = (left + right) / 2; 10 if(nums[mid] == target-nums[i]) 11 return vector<int>({nums[i], nums[mid]}); 12 if(nums[mid] < target-nums[i]) { 13 left = mid + 1; 14 } else { 15 right = mid - 1; 16 } 17 } 18 } 19 20 return vector<int>(); 21 } 22 };
方法二:首尾双指针
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 int i = 0, j = nums.size()-1; 5 while(i < j) { 6 int s = nums[i] + nums[j]; 7 if(s < target) ++i; 8 else if(s > target) --j; 9 else return vector<int>({nums[i], nums[j]}); 10 } 11 12 return vector<int>(); 13 } 14 };