2014
11-19

# LeetCode-Search for a Range[查找]

### Search for a Range

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, Search for a Range
// 偷懒的做法，使用STL
// 时间复杂度O(logn)，空间复杂度O(1)
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
const int l = distance(A, lower_bound(A, A + n, target));
const int u = distance(A, prev(upper_bound(A, A + n, target)));
return vector<int> { -1, -1 };
else
return vector<int> { l, u };
}
};


// LeetCode, Search for a Range
// 重新实现 lower_bound 和 upper_bound
// 时间复杂度O(logn)，空间复杂度O(1)
class Solution {
public:
vector<int> searchRange (int A[], int n, int target) {
auto lower = lower_bound(A, A + n, target);
auto uppper = upper_bound(lower, A + n, target);

if (lower == A + n || *lower != target)
return vector<int> { -1, -1 };
else
return vector<int> {distance(A, lower), distance(A, prev(uppper))};
}

template<typename ForwardIterator, typename T>
ForwardIterator lower_bound (ForwardIterator first,
ForwardIterator last, T value) {
while (first != last) {
auto mid = next(first, distance(first, last) / 2);

if (value > *mid)   first = ++mid;
else                last = mid;
}

return first;
}

template<typename ForwardIterator, typename T>
ForwardIterator upper_bound (ForwardIterator first,
ForwardIterator last, T value) {
while (first != last) {
auto mid = next(first, distance (first, last) / 2);

if (value >= *mid)   first = ++mid;  // 与 lower_bound 仅此不同
else                 last = mid;
}

return first;
}
};


1. 第二块代码if(it != mp.end())应改为if(it != mp.end() && (i+1)!=(it->second +1))；因为第二种解法如果数组有重复元素 就不正确