Leetcode[java] 35. Search Insert Position

来源:互联网 发布:苍空的解放者 知乎 编辑:程序博客网 时间:2024/05/17 03:04

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 res=-1;        int len = nums.length;        if(nums==null||len==0)            return 0;        if(target<=nums[0])            return 0;        else if(target>nums[len-1])            return len;        return binarySearch(target,nums,0,len-1);    }     private int binarySearch(int target,int[] nums, int begin, int end){            if(begin+1==end){        if(target<=nums[begin]){                return begin;            }            else if(target<=nums[end]){                return begin+1;            }        }                    int mid = begin + (end-begin)/2;        System.out.println(mid);        if(target>nums[mid]){                        return binarySearch(target,nums,mid,end);        } else if(target<nums[mid]){                        return binarySearch(target,nums,begin,mid);        } else{            return mid;        }                }}


0 0