Rotated in Sorted Array

1) check is in upper side or lower side

2) check is in left side or right side

code


class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(nums.size() == 0)
        {
            return -1;
        }

        int s = 0;
        int e = nums.size()-1;

        while(s+1 < e)
        {
            int mid = s+(e-s)/2;

            if(nums[mid] == target)
            {
                return mid;
            }

            if(nums[mid] <= nums.back())
            {
                if(target <= nums.back() && target > nums[mid])
                {
                    s = mid;
                }
                else
                {
                    e = mid;
                }
            }
            else
            {
                if(target > nums.back() && target < nums[mid])
                {
                    e = mid;
                }
                else
                {
                    s = mid;
                }
            }
        }

        if(nums[s] == target)
        {
            return s;
        }

        if(nums[e] == target)
        {
            return e;
        }

        return -1;
    }
};

results matching ""

    No results matching ""