[LeetCode-Java]35. Search Insert Position

来源:互联网 发布:linux 日志切割脚本 编辑:程序博客网 时间:2024/06/06 07:45

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

解:又是一个二分查找的问题,未命中则返回待插入位置,命中则继续查找命中起始位置。

public class Solution {    public int searchInsert(int[] nums, int target) {        int len = nums.length;        if (target > nums[len - 1]) return len;        if (target <= nums[0]) return 0;        int lo = 0;        int hi = len - 1;        int mi = 0;        while (lo <= hi){            mi = (lo+hi)/2;            if (nums[mi] == target) break;            else if (nums[mi] > target){                hi = mi -1;            }else {                lo = mi + 1;            }        }        //未命中则返回待插入位置        if (lo > hi) return lo;        //下面用二分查找找到命中的起始位置,也可以用移动指针的方法        hi = mi;        while (lo <= hi){            mi = (lo+hi)/2;            if (nums[mi]==target) hi = mi - 1;            else lo = mi + 1;        }        return lo;    }}
0 0
原创粉丝点击