my c++ solution


  • 0
    W
    class Solution {
    public:
        int helper(vector<int>& nums,int left,int right,int target){
            if(left==right){
                if(target==nums[left]) return left;
                else return -1;
            }
            else if(left > right) return -1;
            else{
                int mid=(left+right)/2;
                if(target==nums[mid]) return mid;
                if(target==nums[left]) return left;
                if(target==nums[right]) return right;
                if(nums[mid]>nums[left] && nums[mid]<nums[right]){
                    if(target>nums[mid]){
                        return helper(nums,mid+1,right-1,target);
                    }else{
                        return helper(nums,left+1,mid-1,target);
                    }
                }
                else if(nums[mid]>nums[left] && nums[mid]>nums[right]){
                    if(target>nums[mid]){
                        return helper(nums,mid+1,right-1,target);
                    }else{
                        if(target>nums[left]) return helper(nums,left+1,mid-1,target);
                        else return helper(nums,mid+1,right-1,target);
                    }
                }
                else{
                    if(target<nums[mid]){
                        return helper(nums,left+1,mid-1,target);
                    }
                    else{
                        if(target>nums[right]) return helper(nums,left+1,mid-1,target);
                        else return helper(nums,mid+1,right-1,target);
                    }
                }
            }
    
        }
        int search(vector<int>& nums, int target) {
            return helper(nums,0,nums.size()-1,target);
        }
    };
    

Log in to reply
 

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