[LeetCode] 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]
分析:排序数组,使用二分查找。
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int result_array[] = {-1, -1}; vector<int> result(result_array, result_array + 2); if (nums.empty()) return result; int start = FindStart(nums, 0, nums.size() - 1, target); int end = FindEnd(nums, 0, nums.size() - 1, target); result[0] = start; result[1] = end; return result; } int FindStart(vector<int>& nums, int start, int end, int target) { if (start > end) return -1; while (start < end) { int mid = start + (end - start) / 2; if (nums[mid] == target) { end = mid; } else if (nums[mid] > target) { end = mid - 1; } else { start = mid + 1; } } return nums[start] == target ? start : -1; } int FindEnd(vector<int>& nums, int start, int end, int target) { if (start > end) return -1; while (start < end) { int mid = start + (end - start) / 2; if (start == end - 1) { if (nums[start] == target) { if (nums[start] == nums[end]) return end; else return start; } } if (nums[mid] == target) { start = mid; } else if (nums[mid] > target) { end = mid - 1; } else { start = mid + 1; } } return nums[end] == target ? end : -1; } };