# 540. Single Element in a Sorted Array

Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.

Example 1:

``````Input: [1,1,2,3,3,4,4,8,8]
Output: 2
``````

Example 2:

``````Input: [3,3,7,7,10,11,11]
Output: 10
``````

Note: Your solution should run in O(log n) time and O(1) space.

1  1  2  2  3

1  2  2  3  3

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

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

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

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

https://discuss.leetcode.com/topic/83310/short-compare-nums-i-with-nums-i-1

https://discuss.leetcode.com/topic/82235/java-code-by-using-binary-search-o-log-n

https://discuss.leetcode.com/topic/82332/java-binary-search-o-log-n-shorter-than-others

https://discuss.leetcode.com/topic/87424/java-binary-search-short-7l-o-log-n-w-explanations

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation