题目描述:
题解一
class Solution {
public int searchInsert(int[] nums, int target) {
int i=0;
while(i<nums.length)
{
if(nums[i]>=target)
{
return i;
}
if(nums[i]<target )
{
i++;
}
}
return i;
}
}
题解二—使用二分查找算法
使用算法前提:数组是一个有序数组,例如:{1,3,7,12,23,…}
二分查找算法的时间复杂度为o(log(n))
代码实现:
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] == target) {
return mid;
} else if(nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}