只出现一次的数字

GitHub跳转原题关系图返回列表

异或所有元素,成对元素异或为 0,最终结果即为只出现一次的数。

OJ: leetcodecn

题目 ID: single-number

难度:入门

标签:位运算技巧

日期: 2026-07-29 13:00

题意

找出数组中唯一只出现一次的数(其余均出现两次)。

思路

利用异或性质:x ^ x = 0x ^ 0 = x,异或满足交换律和结合律。将所有元素异或起来,成对元素互相抵消,结果就是只出现一次的数。

代码

cpp
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int singleNumber(vector<int> &nums) {
        int ans = 0;
        for (int x : nums)
            ans ^= x;
        return ans;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int> a(n);
    for (int &x : a)
        cin >> x;
    cout << Solution().singleNumber(a) << '\n';
    return 0;
}
python
#!/usr/bin/env python3
from typing import List


class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ans = 0
        for x in nums:
            ans ^= x
        return ans


def main():
    n = int(input())
    a = list(map(int, input().split()))
    print(Solution().singleNumber(a))


if __name__ == "__main__":
    main()

复杂度

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)

总结

异或去重是位运算的经典技巧:x ^ x = 0 保证成对元素消除,x ^ 0 = x 保证结果保留。