c++ binary search (9 ms)


  • 0
    class Solution {
      public:
        vector<int> searchRange(vector<int>& nums, int target) {
          int n = nums.size();
          vector<int> ans = {-1, -1};
          int l = 0, r = n;
          while (l < r) {
            int mid = (l + r) >> 1;
            if (nums[mid] >= target) r = mid;
            else l = mid + 1;
          }
          if (nums[r] == target) ans[0] = r;
          l = 0, r = n;
          while (l < r) {
            int mid = (l + r) >> 1;
            if (nums[mid] > target) r = mid;
            else l = mid + 1;
          }
          if (nums[l - 1] == target) ans[1] = l - 1;
          return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.