Core Idea During the search, we continuously narrow down the search interval.
When nums[mid] >= target: target may be to the left of mid, so set right = mid - 1.
When nums[mid] < target: target is to the right of mid, so set left = mid + 1.
Each time nums[mid] == target, record index = mid.
When the loop ends, left exceeds right. The last recorded index must be the leftmost position where nums[index] == target: because each time we encounter target, we still try to narrow the interval to the left (right = mid - 1).
classSolution { public: vector<int> searchRange(vector<int> &nums, int target) { int n = nums.size(); int left = 0, right = n - 1; int mid;
vector<int> res; int index = -1; while (left <= right) { //Find Left Boundary mid = left + (right - left) / 2; if (nums[mid] >= target) { right = mid - 1; } else { left = mid + 1; } if (nums[mid] == target) index = mid; }
res.push_back(index);
left = 0; right = n - 1; index = -1; while (left <= right) { // right boundary mid = left + (right - left) / 2; if (nums[mid] <= target) { left = mid + 1; } else { right = mid - 1; } if (nums[mid] == target) index = mid; } res.push_back(index);
classSolution { private: intsearch_range_end(vector<int> &nums, int target) { int n = nums.size(); int left = 0, right = n - 1, mid; while (left < right) { mid = left + (right - left + 1) / 2; if (nums[mid] <= target) left = mid; else right = mid - 1; }
return (nums[left] == target) ? left : -1; } intsearch_range_start(vector<int> &nums, int target) { int n = nums.size(); int left = 0, right = n - 1, mid; while (left < right) { mid = left + (right - left) / 2; if (nums[mid] >= target) right = mid; else left = mid + 1; }
return (nums[left] == target) ? left : -1; }
public: vector<int> searchRange(vector<int> &nums, int target) { if (nums.empty()) return { -1, -1 };