zoukankan      html  css  js  c++  java
  • 【数组】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.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

    思路:

    二分查找。其中特别注意的是:middle=(low+high)/ 2 ,可能会溢出,可以替换为middle = low + Math.ceil((high - low)/2)

    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number}
     */
    var searchInsert = function(nums, target) {
        var l=0,r=nums.length-1,middle;
        while(l<=r){
            middle=l+Math.floor((r-l)/2);
            if(nums[middle]>target){
                r=middle-1;
            }else if(nums[middle]<target){
                l=middle+1;
            }else{
                return middle;
            }
        }
        return l;
    };
  • 相关阅读:
    django初识
    django前奏
    前端之bootstrap
    前端之jQuery
    前端基础之BOM和DOM操作
    前端之js
    前端之css(二)
    前端之css(一)
    html之form表单
    前端之html
  • 原文地址:https://www.cnblogs.com/shytong/p/5110210.html
Copyright © 2011-2022 走看看