一、数组没有重复数字
1、数字不重复,找到taget的位置,找不到返回-1
public static int erfenfa1(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (target == nums[mid]) {
return mid;
} else if (target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
2、数字不重复,找到taget的位置,找不到返回应该插入的位置
public static int erfenfa2(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (target == nums[mid]) {
return mid;
} else if (target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
二、数组有重复数字
解答
https://blog.csdn.net/u014429653/article/details/118256547
1、数字可能重复,找到taget的位置,找不到返回应该插入的位置,如果数组中已存在target,返回插入第一个的位置
public static int erfenfa3(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (target <= nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
2、数字可能重复,找到taget的位置,找不到返回应该插入的位置,如果数组中已存在target,返回最后一个后应该插入的的位置
public static int erfenfa4(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}