package NC;
/**
* NC105 二分查找-II
*
* 请实现有重复数字的升序数组的二分查找
* 给定一个 元素有序的(升序)整型数组 nums 和一个目标值 target ,
* 写一个函数搜索 nums 中的第一个出现的target,如果目标值存在返回下标,否则返回 -1
*
* @author TANG
* @date 2021/9/27
*/
public class BinarySearch {
public int search (int[] nums, int target) {
// write code here
if(nums.length == 0) {
return -1;
}
int begin = 0;
int end = nums.length - 1;
int result = -1;
while(begin <= end) {
int mid = (end + begin) / 2;
if(nums[mid] == target) {
//找到目标值
result = mid;
break;
}
if(nums[mid] > target) {
end = mid - 1;
}else {
begin = mid + 1;
}
}
if(result < 0) {
return result;
}
//找到最靠前的result
while(nums[result] == target) {
if(result > 0 && nums[result - 1] == target) {
result--;
}else {
break;
}
}
return result;
}
public static void main(String[] args) {
int[] num = {-2};
System.out.println(new BinarySearch().search(num, -3));
}
}