Day4. Search Insert Position(35)

问题描述
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

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

思路1:直接查找

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    for(let i=0;i<nums.length;i++){
        if(nums[i]>=target){
            return i;
        }     
    }  
    if(nums[nums.length-1]<target){
        return nums.length;
    }
};

思路2:二分查找

var searchInsert = function(nums, target) {
    var low = 0;
    var high = nums.length - 1;
    while (low <= high) {
        var mid = Math.floor((low + high) / 2);
        if(nums[mid] < target) {
            low = mid + 1;
        }
        else if(nums[mid] > target){
            high = mid - 1;
        }
        else {
            return mid;
        }
    }
    return high + 1;
};
    原文作者:前端伊始
    原文地址: https://www.jianshu.com/p/cf6b404dcbe9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞