标签:https 查找 col ref lan 方法 span return mamicode
遍历每个数字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 };
面试题57. 和为 s 的两个数字(双指针 + 证明,清晰图解)
标签:https 查找 col ref lan 方法 span return mamicode
原文地址:https://www.cnblogs.com/FengZeng666/p/13971198.html