标签:nlog get family tor input 一个 数组 指针 break
题意:对于一个有序数组,输出和为target的两个元素的下标。题目保证仅有唯一解。
分析:
法一:二分。枚举第一个元素,二分找另一个元素,时间复杂度O(nlogn),非最优解。
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int len = numbers.size(); vector<int> ans; for(int i = 0; i < len; ++i){ int tmp = target - numbers[i]; int l = i + 1; int r = len - 1; bool ok = false; while(l <= r){ int mid = l + (r - l) / 2; if(numbers[mid] == tmp){ ok = true; ans.push_back(i + 1); ans.push_back(mid + 1); break; } else if(numbers[mid] < tmp){ l = mid + 1; } else{ r = mid - 1; } } if(ok){ break; } } return ans; } };
法二:双指针,head和tail分别指向数组中头尾元素,若numbers[head]+numbers[tail]>target,则tail--;若numbers[head]+numbers[tail]<target,则head++;直到numbers[head]+numbers[tail]==target。时间复杂度O(n)。
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> ans; int head = 0; int tail = numbers.size() - 1; while(head < tail){ int sum = numbers[head] + numbers[tail]; if(sum == target){ ans.push_back(head + 1); ans.push_back(tail + 1); break; } else if(numbers[head] + numbers[tail] < target) ++head; else --tail; } return ans; } };
LeetCode167. Two Sum II - Input array is sorted(双指针)
标签:nlog get family tor input 一个 数组 指针 break
原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12288941.html