Input array is sorted -(雙重迴圈break continue)
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、Arrays.sort(陣列名)
預設從小到大給陣列排序
2、continue
立即結束本次迴圈,繼續執行下一次迴圈
3、break
跳出一個迴圈或者結束一個迴圈,若是雙重迴圈,break在內層,則只跳出內層迴圈;若break寫在外層迴圈內,則跳出整個迴圈
bug: 不能省最後的return
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] index = new int[2];
int len = numbers.length;
for(int i=0;i<len;i++){
for(int j=len-1;j>=0;j--){
if(numbers[i]+numbers[j]<target){
break ;
}else if(numbers[i]+numbers[j] == target){
index[0] = i + 1;
index[1] = j + 1;
Arrays.sort(index);
return index;
}
}
}
return index;//不能省
}
}