3ms Solution c++


  • 0

    class Solution {
    public:
    int search(vector<int>& nums, int target) {

        if(nums.size()==0)return -1;
        if(nums.size()==1)
            if(target==nums[0])return 0;
            else return -1;
        if(nums.size()==2){
            if(target==nums[0])return 0;
            if(target==nums[1])return 1;
            return -1;
        }
        int t=nums.size()-1,h=0,c=(h+t)/2,c0=INT_MAX;
        if(target<nums[h]&&target>nums[t])return -1;
        while(nums[t]<nums[h]&&c0!=c){
            if(nums[c]==target)return c;
            if(target==nums[h])return h;
            if(target>nums[h]){
                if(target<nums[c])t=c;
                else{ 
                    if(nums[c]<nums[h])t=c;
                    else h=c;
                }
                c0=c;
                c=(h+t)/2;
                continue;
            }
            if(target==nums[t])return t;
            else if(target<nums[t]){
                if(target>nums[c])h=c;
                else if(nums[c]>nums[h])h=c;
                else t=c;
                c0=c;
                c=(h+t)/2;
                continue;
            }
            
        }
        if(nums[t]==target)return t;
        if(nums[h]==target)return h;
        while(h<t&&c0!=c){
            if(nums[c]<target)h=c;
            else t=c;
            c0=c;
            c=(h+t)/2;
        }
        if(nums[t]==target)return t;
        if(nums[h]==target)return h;
        return -1;
    }
    

    };


Log in to reply
 

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