LeetCode | 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.
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
tags:binary search(注意:二分法只适用于有序的数组)
在使用二分法时,要多注意边界问题,low、high
Java中将小数转换为int时,总是采用截尾的方法:int(1.2)=int(1.9)=1。当想要四舍五入时要使用Java.lang.Math.round():Math.round(1.2)=1,Math.round(1.9)=2
public class Solution { public int searchInsert(int[] A, int target) { if(A.length == 0) return -1; if(target < A[0]) return 0; //排除两种极端情况 if(target > A[A.length-1]) return A.length; int low = 0; int high = A.length-1; while(low <= high){ //标准的二分法查找 int middle = (low+high)/2; if(target == A[middle]) return middle; if(target < A[middle]) high = middle-1; if(target > A[middle]) low = middle+1; } return low; //return high是错的 //分析:如果在二分法中没有找到target,那么在最后一次while循环时,low是小于target的最大元素,high是大于target的最小元素(如果不是这个状态,肯定不是while的最后一次循环),且low与high中间没有其他元素(如果有的话肯定继续循环下去)。然后middle=(low+high)/2=low【截尾】,接下来判断:如果target<A[middle]=A[low],low不变,返回low。如果target>A[middle]=A[low],low+1,返回low。 } }