Leetcode167

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.

solution:

#include <iostream>
#include <vector>

using namespace std;

// 时间复杂度:o(n)
// 空间复杂度:o(1)
// 用了对撞指针的思路
class Solution{
public:
    vector<int> twoSum(vector<int>& numbers, int target){

        int l = 0, r = numbers.size()-1;
        while ( l < r) {
            if ( numbers[l] + numbers[r] == target) {
                int res[2] = {l+1, r+1};
                return vector<int>(res, res + 2);
            }
            else if ( numbers[l] + numbers[r] < target)
                l ++;
            else
                r --;
            }

    }
};

int main(){

    return 0;
}

总结:
这道题有一个暴力解法,时间复杂度为o(n**2):设置两个指针,用双重循环,在所有可能的解中找出等于目标值的两个数,返回索引
还有一种思路(有时间实现一下):因为有序,想到了二分查找,最开始指针i指向第一个元素,然后后面的元素用二分查找找出target-nums[i]的值是否存在,否则i++继续查找。

猜你喜欢

转载自blog.csdn.net/hghggff/article/details/81950931