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.
Note:
- 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.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
方法1:
双层遍历,时间复杂度O(N*N)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] newArray=new int[2];
for(int i=0;i<numbers.length-1;i++){
for(int j=i+1;j<numbers.length;j++){
if(numbers[i]+numbers[j]==target){
newArray[0]=i+1;
newArray[1]=j+1;
return newArray;
}
}
}
return null;
}
}
方法二:
方法一的暴力解法没有充分利用原数组的性质--有序
有序?如果有序的话想到二分搜索。
二分搜索法是O(lgN)的复杂度,所以总的时间复杂度是O(n lgN)的复杂度,比O(N*N)快了很多倍
class Solution {
public int[] twoSum(int[] numbers, int target) {
int length=numbers.length;
if(length<2)
return null;
int[] newArray=new int[2];
for(int i=0;i<length-1;i++){
int index=binearySearch(numbers,i+1,length-1,target-numbers[i]);
if(index!=-1){
newArray[0]=i+1;
newArray[1]=index+1;
return newArray;
}
}
return null;
}
//[l,r]
private int binearySearch(int[]numbers,int l,int r,int target){
while(l<=r){
int mid=l+(r-l)/2;
if(numbers[mid]==target)
return mid;
if(numbers[mid]>target){
r=mid-1;
}else{//numbers[mid]<target
l=mid+1;
}
}
return -1;
}
}
方法三、
对撞指针,时间复杂度为O(n),空间复杂度为O(1)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int i=0,j=numbers.length-1;
while(i<j){
if(numbers[i]+numbers[j]==target){
int[]newArray=new int[2];
newArray[0]=i+1;
newArray[1]=j+1;
return newArray;
}else if(numbers[i]+numbers[j]<target){
i++;
}else{
j--;
}
}
return null;
}
}