leetcode Two Sum II

来源:互联网 发布:java项目的工作流程 编辑:程序博客网 时间:2024/05/16 17:25

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. Please note that 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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题意:给定有序数组和一个目标数,从数组中找到两个数的和为目标数。
1、最容易想到的思路—遍历,时间复杂度O(n^2);

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        int index1 = 0;        int index2 = 0;        int flag = 0;        for(; index1 < numbers.size() - 1; ++index1) {            int temp = target - numbers[index1];            flag = 0;            for (index2 = index1+1; index2 < numbers.size(); index2++) {                if (temp == numbers[index2]){                    flag = 1;                    break;                }                                }            if(flag)                break;        }        if(flag) {            vector<int> ans;            ans.push_back(index1+1);            ans.push_back(index2+1);            return ans;        }        //return;    }};

2、思路:由于数组是有序的,定义两个下标,一个指向最小数,一个指向最大数,若它们的和大于目标数,则右侧下标左移,若它们的和小于目标数,则左侧下标右移。时间复杂度O(n);

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        int low=0, high=numbers.size()-1;        while (numbers[low]+numbers[high]!=target){            if (numbers[low]+numbers[high]<target){                low++;            } else {                high--;            }        }        return vector<int>({low+1,high+1});    }};