Error message here!

Hide Error message here!

Error message here!

Hide Error message here!

Error message here!

Close

## 【LeetCode】Search Insert Position

___Moongazer 2019-09-12 11:04:00 阅读数:15 评论数:0 点赞数:0 收藏数:0

【Description】

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.

Example 1:

```Input: [1,3,5,6], 5
Output: 2
```

Example 2:

```Input: [1,3,5,6], 2
Output: 1
```

Example 3:

```Input: [1,3,5,6], 7
Output: 4
```

Example 4:

```Input: [1,3,5,6], 0
Output: 0```

【AC code】

``` class Solution {
public int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= target) return i;
}
return nums.length;
}
}```
View Code

``` class Solution {
public int searchInsert(int[] nums, int target) {
int arrlen = nums.length;
if (nums[arrlen - 1] < target) return arrlen;
int left = 0, right = arrlen - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] > target) right = mid - 1;
else if (nums[mid] < target) left = mid + 1;
else return mid;
}
return left;
}
}```
View Code

https://www.cnblogs.com/moongazer/p/11510798.html