您的位置:首页 > 其它

LeetCode - Refresh - Search for a Range

2015-03-23 12:56 337 查看
Actually, we are searching the right end of the target so:

1. start could be same as end

2. A[mid] > target, shift to left

3. A[mid] <= target shift to right

class Solution {
public:
int bsearch(int A[], int start, int end, int target) {
int index = -1, mid = 0;
while (start <= end) {
mid = (start + end)/2;
if (A[mid] <= target) {
start = mid + 1;
index = mid;
} else {
end = mid - 1;
}
}
return index;
}
vector<int> searchRange(int A[], int n, int target) {
vector<int> result(2, -1);
result[0] = bsearch(A, 0, n-1, target-1) + 1;
result[1] = bsearch(A, 0, n-1, target);
if (result[0] == -1 || A[result[0]] != target) {
return vector<int> (2, -1);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: