标签:lse insert 图片 ima class 搜索 二分查找 int com
二分查找,注意如果target不在数组中时,需要判断一下下标
class Solution {
public int searchInsert(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;
}
else if(nums[mid] > target){
right = mid - 1;
}
else{
left = mid + 1;
}
}
if(target > nums[left]){
return left + 1;
}
return left;
}
}
标签:lse insert 图片 ima class 搜索 二分查找 int com
原文地址:https://www.cnblogs.com/realzhaijiayu/p/13333969.html