LeetCode Solutions
540. Single Element in a Sorted Array
Time: $O(\log n)$ Space: $O(1)$
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0;
int r = nums.size() - 1;
while (l < r) {
int m = (l + r) / 2;
if (m & 1)
--m;
if (nums[m] == nums[m + 1])
l = m + 2;
else
r = m;
}
return nums[l];
}
};
class Solution {
public int singleNonDuplicate(int[] nums) {
int l = 0;
int r = nums.length - 1;
while (l < r) {
int m = (l + r) / 2;
if (m % 2 == 1)
--m;
if (nums[m] == nums[m + 1])
l = m + 2;
else
r = m;
}
return nums[l];
}
}
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
l = 0
r = len(nums) - 1
while l < r:
m = (l + r) // 2
if m % 2 == 1:
m -= 1
if nums[m] == nums[m + 1]:
l = m + 2
else:
r = m
return nums[l]