Leetcode - Letter Combinations of a Phone Number
Leetcode - Insert Delete GetRandom O(1)

Leetcode - Search Insert Position

violet posted @ Jun 11, 2020 01:01:50 AM in 算法 with tags Algorithm Golang BinarySearch , 293 阅读

https://leetcode.com/problems/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

 

func searchInsert(nums []int, target int) int {
    left := 0
    right := len(nums)
    var mid int
    for left <= right {
        mid = left + (right - left)/2
        if mid >= len(nums) {
            return len(nums)
        }
        if nums[mid] == target {
            return mid
        }
        if nums[mid] < target {
            left = mid + 1
        } else {
            right = mid - 1
        }
    }
    return left
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter