leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0034.cpp (1011B)
0 class Solution { 1 int binary_search_left(const vector<int> &nums, int target) { 2 int low = 0, high = nums.size() - 1; 3 while (low <= high) { 4 int mid = low + (high - low) / 2; 5 if (nums[mid] >= target) 6 high = mid - 1; 7 else 8 low = mid + 1; 9 } 10 return low; 11 } 12 13 int binary_search_right(const vector<int> &nums, int target) { 14 int low = 0, high = nums.size() - 1; 15 while (low <= high) { 16 int mid = low + (high - low) / 2; 17 if (nums[mid] <= target) 18 low = mid + 1; 19 else 20 high = mid - 1; 21 } 22 return high; 23 } 24 25 public: 26 vector<int> searchRange(const vector<int> &nums, const int target) { 27 const int low = binary_search_left(nums, target); 28 if (low >= nums.size() || nums[low] != target) return {-1, -1}; 29 const int high = binary_search_right(nums, target); 30 return {low, high}; 31 } 32 };