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.
Tip:保证数组中没有重复的数字
public class SearchInsertPositionSolution {
public int searchInsert(int[] nums, int target) {
/**
* 查找问题
* 这里使用二分查找法
*/
int high = nums.length - 1;
int low = 0;
while (high >= low) {
int mid = (high + low) >>> 1;//等价于/2,效率略高
if (nums[mid] == target) {
return mid;
} else if (target > nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
}