Skip to content

Latest commit

 

History

History
28 lines (25 loc) · 628 Bytes

35.md

File metadata and controls

28 lines (25 loc) · 628 Bytes

https://leetcode-cn.com/problems/search-insert-position

思路

双指针, 二分查找

代码

var searchInsert = function(nums, target) {
    let left = 0;
    let right = nums.length - 1
    while (left <= right) {
        const mid = left + right >> 1
        const midValue = nums[mid];
       if (midValue === target) {
          return mid;
        } else if (midValue < target) {
          left = mid + 1;
       } else {
         right = mid - 1;
       }
     }
    return left
};

复杂度

时间复杂度:O(logn) 空间复杂度: O(1)