Search Insert Position

来源:互联网 发布:苹果手机价格评估软件 编辑:程序博客网 时间:2024/05/01 18:19

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

思路:binary search,注意头和尾的处理。

public class Solution {     public int searchInsert(int[] nums, int target) {         if(nums == null || nums.length == 0) return -1;         int start = 0; int end = nums.length-1;         while(start<=end){             int mid = start +(end-start)/2;             if(nums[mid] == target){                 return mid;             } else {                 if(nums[mid] < target){                     if(mid+1 == nums.length){                         return nums.length;                     } else if(target < nums[mid+1]) {                         return mid+1;                     }else {                         start = mid+1;                     }                 } else { // target < nums[mid];                     if(mid-1 == -1){                         return 0;                     } else if(nums[mid-1]< target){                         return mid;                     } else {                         end = mid-1;                     }                 }             }         }         return -1;     } }

0 0