---
# System prepended metadata

title: 540. Single Element in a Sorted Array
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    background: transparent;
}
::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #2BE8CF60 0%, #2B83E860 100%);
    border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #2BE8CF95 0%, #2B83E895 100%);
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 540. Single Element in a Sorted Array

###### Link : https://leetcode.com/problems/single-element-in-a-sorted-array/description/

## 題目
給一陣列只有一個數字為單獨存在，其他皆為成對存在，回傳單獨存在的值，且維持O(log(n))
## 程式碼I

```cpp=
class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        int left = 0, right = nums.size() - 1;
        while(left <= right){
            int mid = (left + right) / 2;//中位數
            //如果中位數和他右邊的數值相同
            if(mid + 1 < nums.size() && nums[mid] == nums[mid + 1]){
                //奇數需改變右邊邊界為mid - 1
                //偶數需改變左邊邊界為mid + 2 (mid + 1為相同值，不須再判斷)
                if(mid & 1) right = mid - 1;
                else left = mid + 2;
            }
            //如果中位數和他左邊的數值相同
            else if(mid - 1 >= 0 && nums[mid - 1] == nums[mid]){
                //奇數需改變左邊邊界為mid + 1
                //偶數需改變右邊邊界為mid - 2 (mid - 1為相同值，不須再判斷)
                if(mid & 1) left = mid + 1;
                else right = mid - 2;
            }
            //如果他和左邊數值不同，且和右邊數值不同，代表他是單獨存在的數值，即為答案
            else return nums[mid];
        }
        //ERROR return -1
        return -1;
    }
};
```

## 程式碼II
```cpp=
class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        int left = 0, right = nums.size() - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (mid & 1) {
                mid--; // make sure mid is even
            }
            if (nums[mid] == nums[mid + 1]) {
                left = mid + 2; // the single element is on the right side
            } else {
                right = mid; // the single element is on the left side
            }
        }
        return nums[left];
    }
};
```