LeetCode——Single Number

LeetCode——Single Number

Question

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Solution

用异或操作,包含两个的元素,异或操作后都为0,最后就剩下那个single number。

Answer

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        for (int i : nums)
            res = res ^ i;
        return res;
    }
};
原文地址:https://www.cnblogs.com/zhonghuasong/p/6658534.html