60.Search Insert Position.md
描述
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
您在真实的面试中是否遇到过这个题?
样例
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.
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
挑战
O(log(n)) time
public class Solution {
/**
* @param A: an integer sorted array
* @param target: an integer to be inserted
* @return: An integer
*/
public int searchInsert(int[] A, int target) {
// write your code here
if(A.length == 0 ){
return 0;
}
if(target < A[0]){
return 0;
}
if(target > A[A.length-1]){
return A.length;
}
int left = 0;
int right = A.length-1;
while(left + 1 < right){
int mid = left + (right-left)/2;
if(A[mid] == target){
return mid;
}else if (A[mid] > target){
right = mid - 1;
} else if(A[mid] < target){
left = mid + 1;
}
}
//重点
//三种情况:
if(A[left] >= target) {
return left;
}
if(target<= A[right] && target > A[left]) {
return right;
}
return right+1;
}
}

浙公网安备 33010602011771号