Fork me on GitHub

【数据结构】算法 搜索插入位置 Search Insert Position

搜索插入位置 Search Insert Position

A sorted array of distinct integers and a target value, return the index of the array if the target is found. If not, return the index where it should be if it were inserted in order.

in: nums = [1,3,5,6], target = 5
out:2

思路

找到插入位置,小白的作法,通常都是,从头扫到尾,找到一个插入的位置,ok可以解决。

但是作为一个大白,就不能用这种思路了。果断有效的利用有序数组的条件,进行二分查找。至于what is 二分,问度娘。

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

Tag

Array Binary Search

posted @ 2021-10-10 18:43  WilliamCui  阅读(65)  评论(0编辑  收藏  举报