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.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
给出一个排好序的数组,和一个target,返回target所在的index;如果target不存在,就返回它应该被插入的index.
思路:
时间复杂度是O(logn), 又是sorted array. 想到binary search。
Java有自带的binarySearch函数,
当元素存在时,返回元素所在位置的index, 不存在时,返回-index - 1,
先验证一下自带的binarySearch函数,再自己写一个。
public int searchInsert(int[] nums, int target) {
int index = Arrays.binarySearch(nums, target);
if(index < 0) index = -(index+1);
return index;
}
自己写binarySearch函数。
public int searchInsert(int[] nums, int target) {
int index = binarySearch(nums, target, 0, nums.length-1);
return index;
}
int binarySearch(int[] nums, int target, int left, int right) {
//下一步left,right不包含middle,用<=, 如果left = middle这种包含middle的,用<
while(left <= right) {
int middle = left + (right - left) / 2;
if(nums[middle] == target) {
return middle;
} else if (nums[middle] > target) {
right = middle - 1;
} else {
left = middle + 1;
}
}
return left;
}