# leetcode Search Insert Position

570人阅读 评论(0)

### Search Insert Position

Total Accepted: 4060 Total Submissions: 12013

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

If dropping the left part will break the loop, mid + 1 is the answer;

If dropping the right part will break the loop, mid is the answer;

The AC code is :

class Solution {
public:
int searchInsert(int A[], int n, int target) {
int l = 0, r = n - 1, mid;
while (l <= r) {
mid = (l + r) / 2;
if (A[mid] == target)
return mid;
else if (A[mid] > target) {
if (mid - 1 >= l)
r = mid - 1;
else
return mid;
}
else if (A[mid] < target) {
if (mid + 1 <= r)
l = mid + 1;
else
return mid + 1;
}
}
return mid;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：277063次
• 积分：4649
• 等级：
• 排名：第6532名
• 原创：152篇
• 转载：233篇
• 译文：0篇
• 评论：6条
文章分类
阅读排行
评论排行
最新评论