算法系列——Search Insert Position

来源:互联网 发布:淘宝商品质量问题定义 编辑:程序博客网 时间:2024/06/05 08:23

题目描述

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

解题思路

这是最典型的二分搜索法。while循环的条件是low<=high,如果target和mid指向的值相等,则返回mid,否则根据情况low = mid + 1或者high = mid - 1。这样的好处是,如果找不到该数,high是比该数小的那个数的下标,而low是比该数大的那个数的下标。这题中,我们返回low就行了

程序实现

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