【Lituo】35. Search insertion position
Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order.
Please use an algorithm with time complexity O(log n).
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
提示:
1 <= nums.length <= 1 0 4 10^4 104
- 1 0 4 10^4 104 <= nums[i] <= 1 0 4 10^4 104
nums is an array in ascending order without repeated elements
-1 0 4 10^4104 <= target <= 1 0 4 10^4 104
answer
public class Solution {
public int searchInsert(int[] nums, int target) {
if(nums==null || nums.length==0){
return 0;
}
int left =0;
int right = nums.length -1;
while(left<right){
int mid = left +(right-left)/2;
if(nums[mid]==target){
return mid;
}
else if(nums[mid]>target){
right = mid;
}
else {
left = mid +1;
}
}
//left此时位置的数比目标值小,下一个比目标值大,插入住left+1
if(nums[left]< target){
return left+1;
}
//left此时位置的数比目标值大,前一个比目标值小,直接插入在left位置
else {
return left;
}
}
}