Search Insert Position

来源:互联网 发布:淘宝子账户认证 编辑:程序博客网 时间:2024/06/07 02:40

原题:

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

即给一个排好顺序的数组和一个整数,找到这个整数插到数组应该插的位置。


思考过程:

分析插入过程,所插位置一定是只比它大一点点的数字所在位置。如果是比数组最大元素更大的数就有区别。依旧用二叉搜索。


解题思路:

利用二叉搜索(应该搜不到这个数),达到只剩两个数字的范围。判断target和这两个数字大小,判断插入位置,如果target比最大的还大,那它就插在数组末尾。


结果代码:

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