167. Two Sum II - Input array is sorted
2016-12-24 15:13
435 查看
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int index1=0;
int index2=numbers.length-1;
boolean flag=true;
while(flag){
int l=index1+1,h=index2;
int re=target-numbers[index1];
while(l<=h){
int m=(h+l)/2;
if(re>numbers[m]){
l=m+1;
}
else if(re<numbers[m]){
h=m-1;
}
else {
index2=m;
flag=false;
break;
}
}
index1++;
}
return new int[]{index1,index2+1};
}
}第二种:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int index1=0;
int index2=numbers.length-1;
while(index1<index2){
int v=numbers[index1]+numbers[index2];
if(v==target){
break;
}
else if(v>target)
index2--;
else
index1++;
}
return new int[]{index1+1,index2+1};
}
}
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int index1=0;
int index2=numbers.length-1;
boolean flag=true;
while(flag){
int l=index1+1,h=index2;
int re=target-numbers[index1];
while(l<=h){
int m=(h+l)/2;
if(re>numbers[m]){
l=m+1;
}
else if(re<numbers[m]){
h=m-1;
}
else {
index2=m;
flag=false;
break;
}
}
index1++;
}
return new int[]{index1,index2+1};
}
}第二种:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int index1=0;
int index2=numbers.length-1;
while(index1<index2){
int v=numbers[index1]+numbers[index2];
if(v==target){
break;
}
else if(v>target)
index2--;
else
index1++;
}
return new int[]{index1+1,index2+1};
}
}
相关文章推荐
- 129. Sum Root to Leaf Numbers**
- Javascript基础
- Python中文编码问题
- PHP 反射技术
- 数据流中的中位数
- webstorm 格式化代码及常用快捷键
- Python中的with语句解析和实践
- 消息摘要及其算法扫盲贴
- 9.PHP.ini配置文件中文(2)
- 容易被误解的overflow:hidden
- docker
- 数据结构与算法——线性表 1
- lintcode,搜索二维矩阵
- 大话数据结构-线性表-静态链表
- apach nginx tomcat 负载均衡
- Android 布局优化的几个技巧
- golang读取mysql中null字段出错问题
- 【NOIP2017提高组模拟12.24】C
- 强制关闭Windows下进程
- Xcode8 pod install 报错 “Generating Pods project Abort trap