LeetCode167. Two Sum II - Input array is sorted
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode167. Two Sum II - Input array is sorted相关的知识,希望对你有一定的参考价值。
原题链接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/tabs/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.
想法:
看到排好序的数组,首先就想到了用二分法。对于这道题目,就用目标值和首尾相加去比较,若目标值大,则首指针加1;否则尾指针减1。
代码如下:
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--; } vector<int> res{low + 1,high + 1};//由于返回的是原数组的第几个,而不是下标,所以加1 return res; } };
大部分的排序数组问题都可以用二分法去解决。
以上是关于LeetCode167. Two Sum II - Input array is sorted的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode167. Two Sum II - Input array is sorted
LeetCode 167. Two Sum II - Input array is sorted
[LeetCode] 167. Two Sum II - Input array is sorted
LeetCode:167. Two Sum II - Input array is sorted