- 题目:一个有序数组,查找target在数组中的下标,如果target不在数组中,则返回target应该插入在数组中的位置
- 难度:Easy
- 思路:有序数组查找目标值,肯定是用二分查找,这个题只需在二分查找的基础上稍微目标值的插入位置
- 代码:
public class Solution {
public int searchInsert(int[] nums, int target) {
if(nums == null || nums.length == 0){
return -1;
}
int len = nums.length;
int left = 0;
int right = len-1;
while(left <= right){
int mid = left + (right -left)/2;
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
right = mid-1;
}else {
left = mid+1;
}
}
return left;
}
}