# leetcode Search Insert Position

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

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode Search Insert Position 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)