每天一道leetcode之入门

Day4. Search Insert Position(35)

2017-11-07  本文已影响0人  前端伊始

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

文末彩蛋


艾宾浩斯遗忘曲线
上一篇下一篇

猜你喜欢

热点阅读