您的位置:首页 > 其它

Leetcode: Search for a Range

2014-02-11 23:59 253 查看
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]
.

不难,关键是找到目标之后,怎么处理数组中都是相同元素的情况 - 也需要二分查找。

class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> result;
int low = 0, up = n - 1;
int mid;
while (low <= up) {
mid = (low + up) / 2;
if (A[mid] == target) {
break;
}
else if (A[mid] > target) {
up = mid - 1;
}
else {
low = mid + 1;
}
}

if (low > up) {
result.push_back(-1);
result.push_back(-1);
}
else {
// Handle the same elements in the array
result.push_back(findLeftBound(A, low, mid, target));
result.push_back(findRightBound(A, mid, up, target));
}

return result;
}

int findLeftBound(int A[], int left, int right, int target) {
int mid;
while (left <= right) {
mid = (left + right) / 2;
if (A[mid] == target) {
right = mid - 1;
}
else {
left = mid + 1;
}
}

return left;
}

int findRightBound(int A[], int left, int right, int target) {
int mid;
while (left <= right) {
mid = (left + right) / 2;
if (A[mid] == target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}

return right;
}
};也可以直接找最左和最右的元素。

class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> result;
int low = 0, up = n;
int mid;
while (low < up) {
mid = (low + up) / 2;
if (A[mid] >= target) {
up = mid;
}
else {
low = mid + 1;
}
}

if (A[low] != target) {
result.push_back(-1);
result.push_back(-1);
return result;
}
result.push_back(low);

low = 0, up = n;
while (low < up) {
mid = (low + up) / 2;
if (A[mid] <= target) {
low = mid + 1;
}
else {
up = mid;
}
}
result.push_back(up - 1);

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