Leetcode 167 Two Sum II - Input array is sorted

本文详细解析了LeetCode 167题目的背景及要求,提供了两种高效的解题思路:一是使用双指针法,时间复杂度为O(n);二是采用遍历加二分查找的方法,时间复杂度为O(nlogn)。通过具体实例展示了如何在已排序的整数数组中寻找两数之和等于特定目标值的下标。

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 {};
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值