Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
解题分析:就是一个二分搜索的应用,不难。但是就是注意一个数组越界的检查。LeetCode自己的编译器会报错。
int a,b;
a=num;
b=num;
while(A[a] == target ) a--;
while(A[b] == target ) b++;
最开始的时候,代码是这样的,对二分搜索找到了target,再进行往前往后的找。在codeblocks上运行是无错, 但就是提交在LeetCode上面会出现问题。
最后做了一个数组的溢出判断,终于AC了
int a,b;
a=num;
b=num;
while(A[a] == target && a >= 0) a--;
while(A[b] == target && b <= n-1) b++;
class Solution {
private: int binary_search(int* a, int len, int goal)
{
int low = 0;
int high = len - 1;
while(low <= high)
{
int middle = (low + high)/2;
if(a[middle] == goal)
return middle;
else if(a[middle] > goal)
high = middle - 1;
else
low = middle + 1;
}
return -1;
}
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> s;
int num = binary_search(A,n,target);
if(num == -1) {s.push_back(-1);s.push_back(-1);}
else {
int a,b;
a=num;
b=num;
while(A[a] == target && a >= 0) a--;
while(A[b] == target && b <= n-1) b++;
s.push_back((++a));
s.push_back((--b));
}
return s;
}
};