leetcode-35 Search Insert Position

问题描述:

Given a sorted array and a target value, return the index if thetarget is found. If not, return the index where it would be if it were insertedin 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

问题分析:

    常见的二分查找问题,只不过将查找不到返回-1改为返回start(前一位置即可);

代码:

public class Solution {
   public int searchInsert(int[] nums, int target) {
        int start = 0, end = nums.length - 1;
        while(start <= end) {
            int mid = start + ((end - start) >> 1);
            if(nums[mid] == target)
                return mid;
            else if(nums[mid] > target)
                end = mid - 1;
            else
                start = mid + 1;
        }
        return start;
   }
}
运行结果:

leetcode-35 Search Insert Position_第1张图片

你可能感兴趣的:(leetcode-35 Search Insert Position)