题目:给定一个已按照 非递减顺序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
我的代码:
对撞指针
class Solution {public int[] twoSum(int[] numbers, int target) {int low = 0;//指向头int high = numbers.length - 1;//指向尾while(low<high){if(numbers[low]+numbers[high]==target){return new int[]{low+1,high+1};}else if(numbers[low]+numbers[high]<target){low++;}else{high--;}}return new int[]{-1,-1};}
}
二分法
class Solution {public int[] twoSum(int[] numbers, int target) {for(int i = 0;i<numbers.length;++i){//每轮确定一个元素int low = i+1;//从确定元素的下一个数开始寻找int high = numbers.length-1;while(low<=high){//是可以取等的,因为可以是目标元素int mid = (low+high)/2;if(target-numbers[i]==numbers[mid]){return new int[]{i+1,mid+1};}else if(target-numbers[i]<numbers[mid]){high = mid -1;}else{low = mid+1;}}}return new int[]{-1,-1};}
}
1.二分法还是比较耗时的
2.如果数组无序,可以用暴力法,也是最容易想到的
3.如果有序,那应该自然想到二分查找法