• 【数组】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;
    };
  • 相关阅读:
    信息安全算法
    另类装载问题
    分治法快速排序
    动态规划最长公共子序列
    java网络编程1
    Jndi和会话bean
    EJB初探
    JSF初探
    简单计算器
    关于坐火车
  • 原文地址:https://www.cnblogs.com/shytong/p/5110210.html
Copyright © 2020-2023  润新知