The code can be simplified a bit:

Using examples to see how the binary search works:

size 9 array:

2 2 5 5 7 7 8 8 9

1 2 2 5 5 7 7 8 8

size 7 array:

2 2 3 3 5 5 7

1 2 2 3 3 5 5

Walk through these 4 examples and you will know how the code works. Note that the single number index must be 0, 2, 4, 6, ... etc and cannot be 1, 3, 5, ...

class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0, r = nums.size()-1;
while(l < r) {
int m = l + (r-l)/2;
if(m%2==0) {
if(nums[m]==nums[m+1]) l=m+2;
else r=m;
}
else {
if(nums[m]==nums[m-1]) l=m+1;
else r=m-1;
}
}
return nums[l];
}
};