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].

分析

已经排好了序,用二分查找。

重新实现 lower_bound 和 upper_bound

  1. // Search for a Range
  2. // 重新实现 lower_bound 和 upper_bound
  3. // 时间复杂度O(logn),空间复杂度O(1)
  4. class Solution {
  5. public:
  6. vector<int> searchRange (vector<int>& nums, int target) {
  7. auto lower = lower_bound(nums.begin(), nums.end(), target);
  8. auto uppper = upper_bound(lower, nums.end(), target);
  9. if (lower == nums.end() || *lower != target)
  10. return vector<int> { -1, -1 };
  11. else
  12. return vector<int> {distance(nums.begin(), lower), distance(nums.begin(), prev(uppper))};
  13. }
  14. template<typename ForwardIterator, typename T>
  15. ForwardIterator lower_bound (ForwardIterator first,
  16. ForwardIterator last, T value) {
  17. while (first != last) {
  18. auto mid = next(first, distance(first, last) / 2);
  19. if (value > *mid) first = ++mid;
  20. else last = mid;
  21. }
  22. return first;
  23. }
  24. template<typename ForwardIterator, typename T>
  25. ForwardIterator upper_bound (ForwardIterator first,
  26. ForwardIterator last, T value) {
  27. while (first != last) {
  28. auto mid = next(first, distance (first, last) / 2);
  29. if (value >= *mid) first = ++mid; // 与 lower_bound 仅此不同
  30. else last = mid;
  31. }
  32. return first;
  33. }
  34. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/search/search-for-a-range.html