# 关于二分查找的一些思考

leetcode:剑指 Offer 53 - I. 在排序数组中查找数字 I

0 <= 数组长度 <= 50000

#### 思路一

public int search(int[] nums, int target) {
int index = getIndex(nums,target);
if(index < 0){
return 0;
}
int count = 1;
// 左侧可能还有
for(int i = index-1 ; i >= 0; i--){
if(nums[i] != target){
break;
}
count++;
}
// 右侧可能也还有
for(int i = index+1; i < nums.length; i++){
if(nums[i] != target){
break;
}
count++;
}
return count;
}

public int getIndex(int[] nums, int target){
int left = 0;
int right = nums.length - 1;
while(left <= right){
int mid = (right - left) / 2 + left;
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
right = mid - 1;
}else {
left = mid + 1;
}
}
return -1;
}

### 数组寻值

#### 思路二

public int search(int[] nums, int target) {
if(nums.length == 0){
return 0;
}
int left = 0;
int right = nums.length;
// 寻找左侧边界
while(left < right){
int mid = left + (right-left)/2;
if(nums[mid] == target){
right = mid;
}else if(nums[mid] < target){
left = mid + 1;
}else{
right = mid;
}
}
int leftindex = left;

left = 0;
right = nums.length;
// 寻找右侧边界
while(left < right){
int mid = left + (right-left)/2;
if(nums[mid] == target){
left = mid + 1;
}else if(nums[mid] < target){
left = mid + 1;
}else{
right = mid;
}
}
int rightindex = right - 1;

int count = rightindex - leftindex + 1;
return count;

}