Binary Search - 35. Search Insert Position

时间:2022-07-25
本文章向大家介绍Binary Search - 35. Search Insert Position,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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
    }
}