My C++ Soulution


  • 0
    S

    Its same with https://leetcode.com/discuss/18242/clean-iterative-solution-binary-searches-with-explanation

    /***********************************
     * author : s2003zy
     * weibo  : weibo.com/songzy982
     **********************************/
    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int rLeft = -1;
            int left = 0 , right = nums.size() - 1;
            if (left == right) return nums[left] == target ? vector<int>{left, left} : vector<int>{-1, -1};
            while (left < right) {
                int mid = (left + right) >> 1;
                if (nums[mid] < target) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            rLeft = left;
            right = nums.size() - 1;
            while (left < right) {
                int mid = ((left + right) >> 1) + 1;
                if (nums[mid] > target) {
                    right = mid - 1;
                } else {
                    left = mid;
                }
            }
            return nums[rLeft] != target ? vector<int> {-1, -1} : vector<int> {rLeft, right};
        }
    };

  • 0
    Y
    class Solution {
    

    public:
    vector<int> searchRange(vector<int>& nums, int target) {

        vector<int>res(2);
        res.at(0)=-1;
        res.at(1)=-1;
           if(nums.size()==1)
           {
               if(nums.at(0)==target)
               {
                   res.at(0)=0;
                     res.at(1)=0;
               }
               return res;
           }
        int left,right;
        for(left=0,right=nums.size()-1;left<=right;)
        {
            if(nums.at(left)==target&&nums.at(right)==target)
               break;
          if(nums.at((left+right)/2)>target)
                    right=(left+right)/2-1;
        else if(nums.at((left+right)/2)<target)
                     left= (left+right)/2+1;
          else{
                         if(nums.at(left)!=target)
                         left++;
                         if(nums.at(right)!=target)
                         right--;
             }
        }
        if(left<=right)
       {
                res.at(0)=left;
        res.at(1)=right;
        
          }
          return res;
    }
    

    };


Log in to reply
 

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