插入位置

将元素插入有序数组,采用二分法搜索插入位置,时间复杂度为logn
input:nums=[1,1,2,2,3] target=1 ;
output: return 0
const searchInsert=function(nums:number[],target:number):number{
const n=nums.length
let left=0,right=n-1
while(left<=right){
let mid = ((right-left)>>1)+left
if(target<=nums[mid]){
right=mid-1
}else{
left=mid+1
}
}
return left
}
这篇博客介绍了如何利用二分查找法在已排序的数组中找到合适的位置插入目标元素,从而保持数组的有序状态。示例中展示了输入一个包含重复元素的有序数组[1,1,2,2,3]和目标值1,输出插入位置为0的算法实现。该算法的时间复杂度为O(logn)。
1154

被折叠的 条评论
为什么被折叠?



