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. public class Solution {
  5. public int[] searchRange(int[] nums, int target) {
  6. int lower = lower_bound(nums, 0, nums.length, target);
  7. int upper = upper_bound(nums, 0, nums.length, target);
  8. if (lower == nums.length || nums[lower] != target)
  9. return new int[]{-1, -1};
  10. else
  11. return new int[]{lower, upper-1};
  12. }
  13. int lower_bound (int[] A, int first, int last, int target) {
  14. while (first != last) {
  15. int mid = first + (last - first) / 2;
  16. if (target > A[mid]) first = ++mid;
  17. else last = mid;
  18. }
  19. return first;
  20. }
  21. int upper_bound (int[] A, int first, int last, int target) {
  22. while (first != last) {
  23. int mid = first + (last - first) / 2;
  24. if (target >= A[mid]) first = ++mid; // 与 lower_bound 仅此不同
  25. else last = mid;
  26. }
  27. return first;
  28. }
  29. }

相关题目

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