# 34. Search for a Range

xiaoxiao2021-02-28  14

Given an array of integers sorted in ascending order, 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].

Code(LeetCode运行9ms)

class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> result(2); result[0] = result[1] = -1; if (nums.size() == 0) { return result; } int pos = findTarget(nums, 0, nums.size() - 1, target); result[0] = result[1] = pos; for (int i = pos + 1; i < nums.size(); i++) { if (nums[i] != target) { result[1] = i - 1; break; } else { result[1]++; } } for (int i = pos - 1; i >= 0; i--) { if (nums[i] != target) { result[0] = i + 1; break; } else { result[0]--; } } return result; } int findTarget(vector<int> nums, int start, int end, int target) { if (start > end) { return -1; } int mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { return findTarget(nums, mid + 1, end, target); } else { return findTarget(nums, start, mid - 1, target); } } };