public class SearchInsertPosition {
public int searchInsert(int[] nums, int target) {
int low = 0,high = nums.length-1;
while (low<=high) {
int mid = (low+high)/2;
if(nums[mid] == target)return mid;
else if (nums[mid]<target) {
low = mid+1;
}else if (nums[mid]>target) {
high = mid-1;
}
}
return low;
}
public static void main(String[] args) {
System.out.println(new SearchInsertPosition().searchInsert(new int[] {1,3,5,6},5));
System.out.println(new SearchInsertPosition().searchInsert(new int[] {1,3,5,6},2));
System.out.println(new SearchInsertPosition().searchInsert(new int[] {1,3,5,6},7));
System.out.println(new SearchInsertPosition().searchInsert(new int[] {1,3,5,6},0));
System.out.println(new SearchInsertPosition().searchInsert(new int[] {1,3},0));
}
}
注:当找不到时,low就是要插入的位置!