# Search Insert Position

85人阅读 评论(0)

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;
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1280次
• 积分：110
• 等级：
• 排名：千里之外
• 原创：10篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
阅读排行
评论排行