35. 搜索插入位置 Search Insert Position

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/

posted @ 2020-12-17 14:55  diameter  阅读(67)  评论(0编辑  收藏  举报