leetcode-35. Search Insert Position

来源:互联网 发布:木材砍伐数据 编辑:程序博客网 时间:2024/05/20 05:08

leetcode-35. Search Insert Position

题目:

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

这里首先排除首尾的特殊情况,即添加到0或者添加到nums.length-1的情况,然后再二分查找,只不过对于终止条件的判断需要注意一下,其他没有特别的。

public class Solution {    public int searchInsert(int[] nums, int target) {        int ret = 0,left = 0,right = nums.length-1;        if(nums.length<1) return ret;        if(nums[nums.length-1] < target) return nums.length;        if(nums[0] >= target) return 0;        while(left <= right){            ret = (left + right)/2;            if(nums[ret]==target || (ret !=0 && nums[ret-1]<target && nums[ret]>target)) return ret;            if(nums[ret]<target) left = ret + 1 ;            if(nums[ret]>target) right = ret - 1 ;        }        return ret;    }}
0 0
原创粉丝点击