首页 > 其他 > 详细

35. 搜索插入位置 Search Insert Position

时间:2020-12-17 15:43:30      阅读:24      评论:0      收藏:0      [点我收藏+]

Given a sorted array of distinct integers 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.

Input: nums = [1,3,5,6], target = 5
Output: 2

 

方法:

二分法找到大于等于target的最小值

 

public int searchInsert(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while(l <= r){
            int m = l +(r - l) / 2;
            if(nums[m] == target) return m;
            if(nums[m] > target) r = m - 1;
            else l = m + 1;
        }
        return l;

    }

 

参考链接:

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

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

35. 搜索插入位置 Search Insert Position

原文:https://www.cnblogs.com/diameter/p/14149644.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!