35.搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
Java
public class Solution {
public int searchInsert(int[] nums, int target) {
int index = 0;
int length = nums.length;
if(nums[0] > target)
index = 0;
for(int i=0; i < nums.length-1; i++){
if(nums[i] == target){
index = i;
break;
}
else if(nums[i]<target && nums[i+1]>target){
for(int j=nums.length+1; j==i+1; j--){
nums[j] = nums[j-1];
}
index = i + 1;
}
}
if(nums[length-1]< target ){
index=length;
}
if(nums[length-1]==target)
index = length -1;
return index;
}
}
/*测试代码*/
public class Solution_test {
public static void main(String[] args) {
int[] nums=new int[]{1,3};
int target =3;
int i = new Solution().searchInsert(nums,target);
System.out.println(i);
}
}