两数之和(有序数组)

//有序数组 二分查找
public static int[] solution2(int[] nums,int target){
for (int i=0;i<nums.length;i++){
int low = i, high=nums.length-1;
while (low<=high){
int mid=(high-low)/2+low;
if (nums[mid] == target-nums[I]){
return new int[]{i,mid};
}else if (nums[mid] > target-nums[I]){
high = mid-1;
}else{
low = mid+1;
}
}
}
return new int[0];
}
//双指针
public static int[] solution3(int[] nums,int target){
int low=0,high=nums.length-1;
while (low<high){
int sum = nums[low]+nums[high];
if (sum == target){
return new int[]{low,high};
}else if (sum<target){
low++;
}else {
high++;
}
}
return new int[0];
}

上一篇:2021-07-31 算法笔记Visualgo


下一篇:leecode154. 寻找旋转排序数组中的最小值 II