# 137. Single Number II

## 1.問題&#x20;

* 給予一個整數(正, 負)序列, 每個數字重複3次, 找出只有出現一次的數字

![](/files/-LNY9Yah9tertA0Vu05F)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
* function header, parameter
* test input
* 觀察
  * 識別一個數字是否出現兩次可以用XOR, 但第三次時無法歸零, 因此可以想辦法讓第三次時歸0: & \~(上一次的狀態)
* 說明想法
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int a = 0, b = 0;
        for (int i = 0; i < nums.size(); i++) {
            a = ((a ^ nums[i]) & ~b);
            b = ((b ^ nums[i]) & ~a);
        }
        
        return a | b;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/137.-single-number-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
