Binary Search - 35. Search Insert Position

Published on with 0 views and 0 comments

35. 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.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

思路:

题目意思是给定一个有序数组,和一个target,找出target在数组中的下标,或者应该插入的位置。使用binary search来做。

代码:

go:

func searchInsert(nums []int, target int) int {

    var (
        start = 0
        end = len(nums) - 1
        mid = 0
    )
    for start + 1 < end {
        mid = (end - start) /2 + start
        if target == nums[mid] {
            return mid
        } else if target < nums[mid] {
           end = mid 
        } else {
            start = mid
        }
    }
    
    if target <= nums[start] {
        return start
    } else if target <= nums[end] {
        return end
    } else {
        return end + 1
    }
}

标题:Binary Search - 35. Search Insert Position
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/10/03/1570064498780.html