您的位置:首页 > 其它

Leetcode167. Two Sum II - Input array is sorted

2016-12-02 11:28 501 查看
原题

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

思路

要求:给出一个升序整数数组,找到两个数字,使得加起来达到特定的目标数,注意返回两个数字的索引(索引下标是从1开始的)

思路:1、使用两个指针,双层遍历数组,直至数组中出现两个数的和是目标数,但是这样容易超时,效率低下

代码1

public class Solution {
public int[] twoSum(int[] numbers, int target) {

for(int i=0;i<numbers.length;i++){
for(int j=i+1;j<numbers.length;){
if(numbers[i]+numbers[j]<target)
j++;
else if(numbers[i]+numbers[j]==target)
{
return new int[]{i+1,j+1};
}
else
break;
}
}
return null;
}
}




代码2

思路2,使用数组的一个方法二分搜索算法查找值

public class Solution {
public int[] twoSum(int[] numbers, int target) {
for(int i=0,n=numbers.length;i<n;i++){
//采用二分搜索算法查找值V,如果查找成功,则返回相应的下标值,否则返回一个负数
int j=Arrays.binarySearch(numbers,i+1,numbers.length,target-numbers[i]);
if(j>0)
return new int []{i+1,j+1};
}
return null;
}
}




但是这两种方法效率都不是太高。

原题链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode