# Search Insert Position

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

public class SeachPosition {
public static  int searchInsert(int[] nums, int target) {
int length = nums.length;
//判断target这个元素是否存在数组中，若存在则返回其下标位置
for(int i = 0 ;i < length; i++){
if(nums[i] == target){
return i;
}
}
//新建一个数组，用来做加入target的容器
int[] num = new int[length+1];
for(int i = 0;i < length;i++){
num[i]= nums[i];
}
num[length] = target;
//对新数组进行排序
Arrays.sort(num);
//获取排序后的target的下标
for(int i = 0; i< length+1; i++){
if(num[i]== target){
return i;
}
}
return 0;
}
public static void main(String[] args) {
int[] nums={1,3,4,7};
int target = 2;
int result = searchInsert(nums, target);
System.out.println(result);
}

}

 public static int searchInsert(int[] nums, int target) {
int length = nums.length-1;
int i = 0;
while(i<=length){
int mid = (int)((i+length)/2);
if(target == nums[mid]){
return mid;
}else if(target > nums[mid]){
i = mid +1;
}else{
length = mid - 1;
}
}
return i;
}
• 本文已收录于以下专栏：

举报原因： 您举报文章：Search Insert Position 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)