?LeetCode刷題實(shí)戰(zhàn)167:兩數(shù)之和 II - 輸入有序數(shù)組
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.
題意
輸入: numbers = [2, 7, 11, 15], target = 9
輸出: [1,2]
解釋: 2 與 7 之和等于目標(biāo)數(shù) 9 。因此 index1 = 1, index2 = 2 。
解題
思路1:雙層循環(huán)
class?Solution?{
????public?int[] twoSum(int[] numbers, int?target) {
???????for?(int?i = 0; i < numbers.length; i++) {
????????????int?Num = target - numbers[i];
????????????for?(int?j = i + 1; j < numbers.length; j++) {
????????????????if?(Num == numbers[j]){
????????????????????int?nums[] = {i+1,j+1};
????????????????????return?nums;
????????????????}
????????????}
????????}
????????return?null;
????}
}
思路2:雙指針
class?Solution?{
???public?int[] twoSum(int[] numbers, int?target) {
??????int?left=0;
??????int?right=numbers.length-1;
??????while(left?????????int?sum=numbers[left]+numbers[right];
?????????if(sum==target)return?new?int[]{left+1,right+1};
?????????else?if(sum?????????else?if(sum>target)right--;
??????}
????return?null;
????}
}
思路3:二分查找
class?Solution?{
????public?int[] twoSum(int[] numbers, int?target) {
????????for(int?i = 0; i < numbers.length; i++) {
????????????int?index = binarySearchIndex(numbers, i + 1, target - numbers[i]);
????????????if(index != -1) {
???????????????return?new?int[]{i + 1, index + 1};
????????????}
????????}
????????return?new?int[]{};
????}
????public?int?binarySearchIndex(int[] numbers, int?startIndex, int?target) {
????????int?low = startIndex;
????????int?high = numbers.length - 1;
????????while(low <= high) {
????????????int?mid = (low + high) >>> 1;
????????????if(target > numbers[mid]) {
????????????????low = mid + 1;
????????????} else?if(target < numbers[mid]) {
????????????????high = mid - 1;
????????????} else?{
????????????????return?mid;
????????????}
????????}
????????return?-1;
????}
}
