查找目标值位置
static public int bianrySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==target){
return mid;
}
if(nums[mid]>target){
right=mid-1;
}else{
left=mid+1;
}
}
return -1;
}
如 int[] nums={1,2,3,4,5}; int target=3;
输出结果: 2
查找目标值的下一个值的位置
static public int nextMax(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int ans=nums.length;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>target){
ans=mid;
right=mid-1;
}else{
left=mid+1;
}
}
return ans;
}
如 int[] nums = {1,3,3,5,5,7,7,9,10,10}; int target = 5;
输出结果: 5
查找目标值的上一个值的位置
static public int beforeMin(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int ans=nums.length;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]<target){
ans=mid;
left=mid+1;
}else{
right=mid-1;
}
}
return ans;
}
如 int[] nums = {1,3,3,5,5,7,7,9,10,10}; int target = 5;
输出结果: 2