Share my C++ solution using simple binary search with O(n) space and O(logn) time.


  • 0
    S
        class Solution {
    public:
        int search(vector<int>& nums, int target) {
            int len = nums.size();
            int temp = 0,i,j;
            while(nums[temp] < nums[temp+1]){
                nums.push_back(nums[temp++]);
            }
            nums.push_back(nums[temp]);
            i = temp + 1;
            j = nums.size()-1;
            while(i <= j){
                int mid = i + ((j-i)/2);
                if(nums[mid] > target)
                    j = mid - 1;
                else if(nums[mid] < target)
                    i = mid + 1;
                else 
                    return mid < len ? mid : mid - len; 
            }
            return -1;
        }
    };

Log in to reply
 

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