本文主要是介绍LeetCode-167. Two Sum II - Input array is sorted,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/?tab=Description
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
分析:用left和right分别代表数组小的值和大的值。从首尾开始。如果它们的和>target,说明要减小right。如果它们的和
class Solution {
public:vector<int> twoSum(vector<int>& numbers, int target) {vector<int> res(2,-1);int left=0;int right=numbers.size()-1;while(left<right){int sum=numbers[left]+numbers[right];if(sum==target){res[0]=left+1;res[1]=right+1;return res;}else if(sum>target){right--;}else{left++;}}}
};
这篇关于LeetCode-167. Two Sum II - Input array is sorted的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!