167. Two Sum II

来源:互联网 发布:ubuntu修改hosts翻墙 编辑:程序博客网 时间:2024/06/06 06:30

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


翻译:给定一个数组,这个数组已经排序好了,找到两个数字,使得他们相加的和是一个特定的目标数。

函数twoSun返回两个数字的下标,其中下标1必须小于下标2(返回的数从小到大排序)

可以假设每个输入的目标值都只有一个解决方案,并且不能使用相同的元素相加两次。

分析:只有一个解决方案,也就意味着输出的数组中只有两个数。

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


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小米5x边边裂开怎么办 荣耀8的后盖摔了怎么办 hp打印机卡了纸怎么办 华为荣耀9进水了怎么办 小米5x屏幕脱胶怎么办 小米5x后盖松动怎么办 苹果手机没电了怎么办 荣耀9的后盖裂了怎么办 手机一直在开机画面怎么办华为 华为手机一直显示开机画面怎么办 华为p7手机开不了机怎么办 华为荣耀8弯了怎么办 手机壳掉漆了怎么办 华为5a手机音量小怎么办 华为5a手机声音小怎么办 苹果屏幕磨花了怎么办 白色磨砂手机壳脏了怎么办 胶皮手机壳变黄怎么办 手机壳边缘黑了怎么办 手机壳磨黑了怎么办 iphon8原装后壳碎裂怎么办 皮的手机壳发黄怎么办 荣耀手机一直在开机画面怎么办 玻璃手机壳碎了怎么办 华为6x信号不好怎么办 昂达平板v819i刷成砖了怎么办 华为5x忘记密码怎么办 荣耀8开不了机怎么办 华为5s死机了怎么办 华为重启后忘了解锁密码怎么办 华为mate.9上网速度慢怎么办 华为mate10上网速度慢怎么办 四核豌豆2变砖怎么办 苹果32g不够用怎么办 移动4g网络卡怎么办 移动4g网非常卡怎么办 移动4g卡网速慢怎么办 手机移动4g网卡怎么办 华为手机摄像头进灰怎么办 美图t8忘记密码怎么办 华为mate7忘记开机密码怎么办