# 540. Single Element in a Sorted Array

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/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
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

关键在于题目要求O(log n) time and O(1) space.

先来一个不符合题目要求的 O(N)时间 两行版本吧, 异或

```python
class Solution:
    def singleNonDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        from functools import reduce
        return reduce(operator.xor, nums)
```


> 思路 2
******- 时间复杂度: O(lgN)******- 空间复杂度: O(1)******

lgN 自然而然地会想到二分

- 首先找最中间的那一对数字nums[mid]和nums[mid+1]，使得nums[mid]左边一定还有偶数个数字
- 如果他们不相等，即```nums[mid] != nums[mid+1]```，那么nums[mid]肯定跟它左边邻居nums[mid-1]相等，
然后左边还剩下奇数个数字，所以那个单独的数字肯定在左边
- 如果他们相等，即```nums[mid] == nums[mid+1]```，那么那个单独的数字肯定在右边

参考[thms_la](https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/100754/Java-Binary-Search-short-(7l)-O(log(n))-w-explanations)


beats 89.95%


```python
class Solution:
    def singleNonDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l, r = 0, len(nums) - 1
        while l < r:
            mid = (l + r) // 2
            if mid % 2 == 1:
                mid -= 1
            if nums[mid] != nums[mid+1]:
                r = mid
            else:
                l = mid + 2
        return nums[l]
```

























