Skip to content

Latest commit

 

History

History
140 lines (118 loc) · 3.17 KB

File metadata and controls

140 lines (118 loc) · 3.17 KB

中文文档

Description

Given a sorted array of distinct integers 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.

 

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:

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

Example 4:

Input: nums = [1,3,5,6], target = 0
Output: 0

Example 5:

Input: nums = [1], target = 0
Output: 0

 

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums contains distinct values sorted in ascending order.
  • -104 <= target <= 104

Solutions

Python3

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l, h = 0, len(nums) - 1
        while l <= h:
            m = (l + h) >> 1
            if nums[m] == target:
                return m
            if nums[m] < target:
                l = m + 1
            else:
                h = m - 1
        return l

Java

class Solution {
    public int searchInsert(int[] nums, int target) {
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = (l + h) >>> 1;
            if (nums[m] == target) return m;
            if (nums[m] < target) l = m + 1;
            else h = m - 1;
        }
        return l;
    }
}

Go

func searchInsert(nums []int, target int) int {
    l, h := 0, len(nums) - 1
    for l <= h {
        m := l + ((h - l) >> 1)
        if nums[m] == target {
            return m
        }
        if nums[m] < target {
            l = m + 1
        } else {
            h = m - 1
        }
    }
    return l
}

C++

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int l = 0, h = nums.size() - 1;
        while (l <= h) {
            int m = l + ((h - l) >> 1);
            if (nums[m] == target) return m;
            if (nums[m] < target) l = m + 1;
            else h = m - 1;
        }
        return l;
    }
};

JavaScript

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function (nums, target) {
  let l = 0,
    h = nums.length;
  while (l <= h) {
    const m = (l + h) >>> 1;
    if (nums[m] == target) return m;
    if (nums[m] < target) l = m + 1;
    else h = m - 1;
  }
  return l;
};

...