###### 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 -- LeetCode

2014-03-02 07:40:19

#### Python - Search Insert Position

2016-01-16 19:52:32

#### LeetCode解题报告--Search Insert Position

2015-12-04 16:58:11

#### 【LeetCode-面试算法经典-Java实现】【035-Search Insert Position（搜索插入位置）】

2015-07-27 07:18:33

#### LeetCode 35 Search Insert Position（搜索并插入）

2015-11-28 21:16:01

#### LeetCode35——Search Insert Position

2015-10-15 22:01:06

#### Search Insert Position三种方法解析

2017-02-23 15:21:26

#### LeetCode Search Insert Position查找插入位置

2013-12-04 08:48:00

#### LeetCode 35 Search Insert Position (C,C++,Java,Python)

2015-05-18 20:33:01

#### 搜索插入位置：Search Insert Position

2016-06-17 12:14:47

## 不良信息举报

Search Insert Position