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.
Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

分析

其实就是求小于等于目标值的元素的数量,这样想来的话就简单了,遍历数组直到元素大于等于目标值或i等于数组的长度,返回i。

代码如下:

  public int searchInsert(int[] nums, int target) {
        for(int i=0;;i++)
            if(i == nums.length || nums[i] >= target) return i;
    }

其他方法:

代码很简洁,但是运行时间只打败了10%多的java代码,参考了别人的代码,发现可以用二分查找,比较省时。

代码如下:

  public int searchInsert(int[] nums, int target) {
        int lo=0, hi=nums.length-1;
        while(lo<=hi){
          int mid = lo+(hi-lo)/2;
          if(nums[mid] == target)  return mid;
          else if(nums[mid] < target)  lo = mid+1;
          else  hi=mid-1;
        }
        return lo;
    }

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