您的位置:首页 > 其它

LeetCode: Search Insert Position

2012-10-08 12:17 295 查看
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

标准的二分搜索算法,在结束的时候,如果没有找到target:那么r指向小于target的最大的数,l指向大于target的最小的数。

class Solution {
public:
int binarySearch(int A[], int n, int target)
{
int l = 0;
int u = n - 1;
int p = -1;
while (l <= u)
{
int mid = l + (u-l)/2;
if (A[mid] == target)
{
p = mid;
break;
}
else if (A[mid] < target)
{
l = mid + 1;
}
else
u = mid - 1;
}
return p == -1 ? l : p;
}

int searchInsert(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 0)
return 0;

return binarySearch(A, n, target);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: