## 查找位置 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

Subscribe to see which companies asked this question.

②不需要编写main函数，只要符合算法逻辑即可

③可以调用部分现有的函数，如：Arrays.binarySearch(nums, target);

1.  语言：java

public class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
//若为 <，则会造成结果错误
while(start <= end){
//防止溢出
int mid = (end - start) / 2 + start;
if(target == nums[mid]){
return mid;
}else if(target < nums[mid]){
//若写为end = mid;则会造成超时
end = mid - 1;
}else if(target > nums[mid]){
start = mid + 1;
}
}
return start;
}
}

public class Solution {
public int searchInsert(int[] nums, int target) {
int pos = Arrays.binarySearch(nums, target);
if(pos < 0){

//说明target不存在，此时返回第一个大于target的位置
return -pos - 1;
}else{
return pos;
}
}
}

2. 语言：Python

### 叶枫啦啦

Lintcode60 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 as......

Winnielyn
2018/06/26
0
0
debian默认编辑器nano的用法

2013/07/09
236
0

darlingwood2013
2018/05/30
0
0
TSQL 字符串函数：截断和查找

2015/06/18
0
0
C++ string类中的字符串查找

C++ string类中的字符串查找 类string提供了大量查找功能和搜索功能，其中比较常用的查找和搜索函数是find()函数、 findfirstnotof()函数、findfirstof()函数、findlastnotof()函数、findlas...

simpower
2015/08/07
37
0

import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.os.Environment;import android.provider.MediaStore;import andr......

MrLins

5
0

8
0

Shingfi

4
0

DustinChan

6
0
Excel插入批注：可在批注插入文字、形状、图片

1.批注一直显示：审阅选项卡-------->勾选显示批注选项： 2.插入批注快捷键：Shift+F2 组合键 3.在批注中插入图片：鼠标右键点击批注框的小圆点【重点不可以在批注文本框内点击】----->调出批...

6
1