Leetcode 167 Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:Your returned answers (both index1 and index2) are not zero-based.You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
题目大意:给定一个升序的整数序列,从中找到两个数使它们的和等于某个特定的数并返回这两个数的序号。序号1必须小于序号2。
注意:序号不是从0开始,且可以假设有且只有一种答案。
解题思路1:使用头尾双指针向中心遍历,每次对比两个指针值的和与目标值的大小,小于则头指针左移,大于则尾指针右移,直到找到目标或指针指向相同的目标。此解法时间复杂度为O(n)。
代码:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i = 0;
int j = numbers.size() - 1;
while(i != j)
{
const int sum = numbers[i] + numbers[j];
if(sum == target)
return {i+1, j+1};
else if(sum > target)
j--;
else
i++;
}
return {-1,-1};
}
};
解题思路2:因为题目保证有解,则序号1的数肯定比目标数小,故可对整个序列遍历设定首个数为序号1,再对序号1的数后的序列进行二分查找,直至找到该数加上序号1的数等于目标数。时间复杂度为O(nlogn)。
代码:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
for(int i=0; i<numbers.size(); i++)
{
int temp = target - numbers[i];
int left = i + 1, right = numbers.size() - 1;
while(left <= right)
{
int mid = (right - left) / 2 + left;
if(numbers[mid] == temp)
return {i+1, mid+1};
else if(numbers[mid] > temp)
right = mid - 1;
else
left = mid + 1;
}
}
return {};
}
};
本文详细解析了LeetCode 167题目的背景及要求,提供了两种高效的解题思路:一是使用双指针法,时间复杂度为O(n);二是采用遍历加二分查找的方法,时间复杂度为O(nlogn)。通过具体实例展示了如何在已排序的整数数组中寻找两数之和等于特定目标值的下标。
397

被折叠的 条评论
为什么被折叠?



