c++ code using binary search


  • 0
    class Solution {
    public:
        int singleNonDuplicate(vector<int>& nums) {
            int left = 0, mid, right = nums.size()-1;
            while (left<right) {
                mid=(left+right)>>1;
                if (nums[mid]!=nums[mid-1] && nums[mid]!=nums[mid+1])
                    return nums[mid];
                else if ((mid%2==1 && nums[mid]==nums[mid-1]) || (mid%2==0 && nums[mid]==nums[mid+1]))
                    left=mid+1;
                else
                    right=mid-1;
            }
            return nums[left];
        }
    };
    
    

  • 0
    Y

    I don't know if I'm not considerable. But it seems like some mistake in your coding. When mid%2==0, and nums[mid] matches nums[mid-1] or nums[mid+1], mid should be added 2. ex:{1,1,2,3,3,4,4,5,5}


Log in to reply
 

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