Clear C++ solution using binary search


  • 0
    K
    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            if(nums.empty()) return -1;
            int l=0,r=nums.size()-1,m;
            while(l<r)
            {
                m=l+(r-l)/2;
                if(nums[m]>=nums[0])//check the position of the mid num,the former part
                {
                   if(target>=nums[0]&&nums[m]>=target)
                      r=m;
                   else
                      l=m+1;
                }
                else// the later part
                {
                    if(target<nums[0]&&nums[m]<target)
                        l=m+1;
                    else
                        r=m;
                }
            }
            return (nums[l]==target)?l:-1;
        }
    };

Log in to reply
 

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