167. Two Sum II
来源:互联网 发布:红米note3怎么内存优化 编辑:程序博客网 时间:2024/06/06 07:23
167. Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- 题目描述
- 解题思路
题目描述
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给定一个已经按升序排序的整数数组,找到两个数字,使它们相加到一个特定的目标数。 函数twoSum应该返回两个数字的索引,使它们相加到目标,其中index1必须小于index2。请注意,您返回的答案(index1和index2)都不是基于零的。 您可以假设每个输入都只有一个解决方案,您可能不会使用相同的元素两次。
解题思路
利用二分搜索,在升序的数组中,从头尾开始求和,
然后与target比较选择适当的进行遍历,复杂度O(n)。
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int i = 0, j = numbers.size() - 1; vector<int> v; while(i < j) { int x = numbers[i] + numbers[j]; if(x < target) { i++; } else if(x > target) { j--; } else { v.push_back(i + 1); v.push_back(j + 1); return v; } } }};
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- Activity生命周期与启动模式笔记
- 2017服务外包创新创业大赛感想
- Android TextView的跑马灯效果以及TextView的部分属性
- 什么是面向对象思想
- 注释驱动的 Spring cache 缓存介绍
- 167. Two Sum II
- Maven相关名词、概念-解释总结
- 发布jar包到Maven中央仓库
- ==Tomcat的坑==【eclipse下面 “绿色进度条”一直在闪时,这时就重启 eclipse!!!!】这时候运行项目出不来!(代码没错)
- Python 中编码的问题
- CentOS7 单独分区var空间不足问题
- ListView异步加载图片,完美实现图文混排
- Linux指令学习之crontab 定时执行任务
- SpringCloud(第 005 篇)电影微服务,也注册到 EurekaServer 中,通过 Http 协议访问已注册到生态圈中的用户微服务