题目:Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
给一个已排序数组和一个目标值,返回目标值应该插入的位置
例如
输入:[1,3,5,6],5
输出:2
思路:
用 二分查找 的算法找到目标应该插入的位置
code
func searchInsert(nums []int, target int) int {
if target < nums[0] {
return 0
}
l := len(nums)
if target > nums[l-1] {
return l
}
left, right := 0, l-1
for left <= right {
m := (left + right) / 2
if nums[m] > target {
right = m - 1
if right >= 0 {
if nums[right] < target {
return right + 1
}
} else {
return 0
}
} else if nums[m] < target {
left = m + 1
if left < l {
if nums[left] > target {
return left
}
} else {
return l
}
} else {
return m
}
}
return 0
}
更多内容请移步我的repo: