class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length-1, mid = 1/2*(left + right);
while(left <= right){
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
right = mid - 1;
}else if(nums[mid] < target){
left = mid + 1;
}
mid = left +(right - left)*1/2;
}
return -1;
}
}
第一遍写二分查找的时候我用了
mid = 1/2 *(left + right);
while一直显示超出时间限制,后面改成了下面的式子才过
mid = left + (right - left)* 1/2
推测可能是mid = 1/2 *多少的时候直接变成了0,于是动手试了试,果然是这样:
一旦把 *1/2写在后面,就可以通过测试用例。