6ms C++ code, beats 100%. Easy and no line-saving code


  • 0
    M
    class Solution {
    public:
        bool search(vector<int>& nums, int target) {
            int left = 0, right = nums.size()-1;
            while(left <= right) {
                if (left == right) {
                    return nums[left] == target ? true : false;
                }
                int mid = left + (right-left) / 2;
                if (nums[mid] == target) {
                    return true;
                }
               
               else if (target < nums[mid]) {
                   if (mid-1 >= 0 && nums[mid] < nums[mid-1]) {
                       return false;
                   }
                   //if right part is messed up:
                   else if (nums[mid] > nums[right] && target < nums[left]) {
                       left = mid+1;
                   }
                   //if right part is not messed up:
                   else if (nums[mid] < nums[right]){
                       right = mid-1;
                   }
                   else {
                       right --;
                   }
                }
                else {
                    if (nums[mid] > nums[mid+1]) {
                        return false;
                    }
                    else if (nums[left] > nums[mid] && target > nums[right]) {
                        right = mid-1;
                    }
                    else if (nums[left] < nums[mid]) {
                        left = mid+1;
                    }
                    else {
                        left ++;
                    }
                }
            }
            return false;
        }
    };
    

Log in to reply
 

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