LeetCode[167]Two Sum II - Input array is sorted

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/khy19940520/article/details/77991149
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;
    }
};


猜你喜欢

转载自blog.csdn.net/khy19940520/article/details/77991149