問(wèn)題:
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
大意:
給出一個(gè)遞增排好序的整型數(shù)組恢准,找出兩個(gè)數(shù)組相加等于目標(biāo)數(shù)字丙躏。
函數(shù) twoSum 應(yīng)該返回兩個(gè)數(shù)字的索引莲组,index1 必須小于 index2并闲。請(qǐng)注意你返回的結(jié)果(index1 和 index2)不是基于0開始的吝镣。
你可以假設(shè)每個(gè)輸入都有一個(gè)結(jié)果。
輸入:numbers={2, 7, 11, 15}, target=9
輸出:index1=1, index2=2
思路:
最直接的方法是遍歷每一個(gè)數(shù),然后看它后面的每個(gè)數(shù)與它相加能不能等于目標(biāo)數(shù)字楞遏,但是這樣太慢了鳍徽。
要利用好數(shù)組已經(jīng)排好序的條件资锰,兩個(gè)數(shù)相加一定是一大一小相加得出目標(biāo)數(shù)字,那么我們可以用兩個(gè)游標(biāo)阶祭,一個(gè)從數(shù)組頭開始遍歷绷杜,一個(gè)從數(shù)組尾開始遍歷,如果數(shù)組頭的數(shù)字小于目標(biāo)數(shù)字減去數(shù)組尾的數(shù)字濒募,則數(shù)組頭的游標(biāo)往后移動(dòng)一格鞭盟,否則數(shù)組尾的游標(biāo)往前移動(dòng)一格。如果兩個(gè)數(shù)字相加正好等于目標(biāo)數(shù)字瑰剃,那么結(jié)束循環(huán)將結(jié)果返回齿诉,注意索引要求從1開始,所以我們要將得出得的兩個(gè)索引號(hào)都加一晌姚。
舉個(gè)例子粤剧,數(shù)組為 [1,2,3,4],目標(biāo)數(shù)字為6挥唠,i 和 j 分別一開始在1和4兩個(gè)數(shù)字抵恋,因?yàn)?小于6-4,所以數(shù)組頭的游標(biāo)指向2宝磨,數(shù)組尾的游標(biāo)不變弧关,此時(shí)2+4正好等于6,返回結(jié)果索引為2和4懊烤,而不是1和3梯醒。
代碼(Java):
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
int i = 0;
int j = numbers.length-1;
while (i < j) {
if (numbers[i] + numbers[j] == target) {
result[0] = i+1;
result[1] = j+1;
break;
}
if (numbers[i] < target - numbers[j]) i++;
else j--;
}
return result;
}
}
合集:https://github.com/Cloudox/LeetCode-Record