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.
要求
這道題是給定一個(gè)值target礁扮,然后求升序數(shù)組中是否存在兩個(gè)元素的值相加等于target痪欲,如果相等的話返回對應(yīng)的索引值加1(規(guī)定下標(biāo)從1開始).不存在的話返回[0,0]。而且規(guī)定總是只有一種解法,數(shù)組中的元素只能遍歷一次。
解題思路
因?yàn)閿?shù)組只能遍歷一次,所以分別設(shè)置左指針lef和右指針right,求num[left]和num[right]的和sum,如果這個(gè)和等于target吊洼,則返回left+1和right+1。如果sum>target肮韧,則右指針right--融蹂,反之左指針left++旺订。
反思
自己總想著遍歷每個(gè)數(shù)組需要用到for循環(huán),其實(shí)設(shè)置指針根據(jù)情況自增自減同樣可以實(shí)現(xiàn)超燃。
public int [] twoSum(int [] num, int targte){
int[] indice = new int[2];
if (num == null || num.length < 2) {return indice;}
int left = 0, right = num.length - 1;
while (left < right) {
int sum= num[left] + num[right];
if (sum == target) {
indice[0] = left + 1;
indice[1] = right + 1;
break;
} else if (sum > target) {
right --;
} else {
left ++;
}
}
return indice;
}
}