/**
* 返回target所在索引,没有则返回-1
*
*/
//二分查找的前提是数组有序
public int binarySearch(int[] nums,int target){
int left = 0;
int right = nums.length - 1;
//[left...right]
while(left < right){
//向下取整
//防止两数过大相加溢出
int mid = left + ((right - left) >> 1);
if(nums[mid] == target) return mid;
else if(nums[mid] > target){
right = mid;
}else{//nums[mid] < target
left = mid + 1;
}
}
return -1;
}
二分查找模板
最新推荐文章于 2024-09-02 16:50:54 发布