Given a sorted array of distinct integers 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 must write an algorithm with O(log n)
runtime complexity.
// The right answer
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1 ;
while(left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
right = mid - 1;
}else{
left = mid + 1;
}
}
return left;
/**
code again, code by memory
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) {
right = mid -1;
}
else{
mid = left + 1;
}
return left;
}
}
*/
Tips:
1: Alway rember binary should use while loop not for loop
2: rember your bound;
3: pay attention to the question: Search Insert Position not find the target.
4: the left is the position that we want