Share my solution in C++ using binary search


  • 0
    D
    int singleNonDuplicate(vector<int>& nums) {
            int num_p = ceil(nums.size()*1.0 / 2);
            int idx_s = 0, idx_e = num_p - 1, idx_m = 0;
            while (idx_s < idx_e)
            {
                if (nums[idx_s * 2 + 1] != nums[idx_s * 2] )
                    return nums[idx_s * 2];
                if (nums[idx_e * 2] != nums[idx_e * 2 - 1] )
                    return nums[idx_e * 2];
                idx_m = (idx_s + idx_e) / 2;
                if (nums[idx_m * 2] != nums[idx_m * 2 + 1])
                    idx_e = idx_m;
                else
                    idx_s = idx_m;
            }
            return nums[idx_m];
    }
    

Log in to reply
 

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