您的位置 首页 golang

Golang刷题 LeetCode-35 Search Insert Position

题目: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:

文章来源:智云一二三科技

文章标题:Golang刷题 LeetCode-35 Search Insert Position

文章地址:https://www.zhihuclub.com/97105.shtml

关于作者: 智云科技

热门文章

网站地图