LeetCode[167]Two Sum II

来源:互联网 发布:js获取今天年月日 编辑:程序博客网 时间:2024/05/22 14:54
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


本地可运行程序:

#include<iostream>#include<vector>using namespace std;/*解题思路是先首尾相加,然后相加的值与目标值对比,比目标值小的话,首向右移动,比目标值大的话,尾向左移动。因为数值是从小到大排列,所以这种方法刚好解题。*/vector<int> twoSum(vector<int>& numbers, int target);int main(){vector<int> numbers = { 2,7,11,15 };int target = 9;vector<int> result;result = twoSum(numbers, target);for (int i = 0; i < result.size(); i++){cout << result[i] << endl;}system("pause");return 0;}vector<int> twoSum(vector<int>& numbers, int target){vector<int> result;int i = 0;//首索引int j = numbers.size() - 1;//尾索引while (target-numbers[i] != numbers[j]){if (target - numbers[i] > numbers[j]){i++;//相加值比目标值小,首向右移动}else{j--;//相加值比目标值大,尾向左移动}}result.push_back(i+1);result.push_back(j+1);return result;}

提交程序:

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


原创粉丝点击