二分查找模板
int binary_search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if(nums[mid] == target) {
return mid;
}
}
return -1;
}
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = (right - left) / 2 + left;
if(nums[mid] < target) {
left = mid + 1;
} else if(nums[mid] > target) {
right = mid - 1;
} else if(nums[mid] == target) {
right = mid - 1;
}
}
if(left >= nums.length || nums[left] != target) {
return 0;
}
int left1 = 0, right1 = nums.length - 1;
while(left1 <= right1) {
int mid = (right1 - left1) / 2 + left1;
if(nums[mid] < target) {
left1 = mid + 1;
} else if(nums[mid] > target) {
right1 = mid - 1;
} else if(nums[mid] == target) {
left1 = mid + 1;
}
}
if(right1 < 0 || nums[right1] != target) {
return 0;
}