题目:给定一个排序的整数数组 nums 和一个整数目标值 target ,请在数组中找到 target ,并返回其下标。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/N6YdxV
使用二分法,若数组中存在目标值则返回其下标,若不存在那么返回其应该插入位置的下表,先使用二分法去数组中查找元素,如果找不到的话,返回left
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right){
int mid = (left + right) / 2;
if (target == nums[mid]){
return mid;
}else if (target < nums[mid]){
right = mid - 1;
}else {
left = mid + 1;
}
}
return left;
}



