C++ O(logn) easy to understand


  • 0
    J
    class Solution {
    public:
        int singleNonDuplicate(vector<int>& nums) {
            int len=nums.size();
            int start=0;
            int end=len-1;
            while(start<end)
            {
                int mid=start+(end-start)/2;
                bool dir=checkDir(mid, nums);
                if(dir == true) //go right
                {
                    start=mid+1;
                }
                else //go left
                {
                    end=mid;
                }
            }
            return nums[start];
        }
        
        bool checkDir(int mid,vector<int>& nums)
        {
            if(mid%2==0)
            {
                if(nums[mid]==nums[mid+1])
                {
                    return true; //right
                }
                else
                    return false;//left
            }
            else
            {
                if(nums[mid]==nums[mid-1])
                {
                    return true;//right
                }
                else
                    return false; //left
            }
        }
    };
    

Log in to reply
 

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