136. Single Number

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?

这个题跟《编程之美》里的 快速找出故障机器 的原理是一样的
把nums里的所有值进行异或运算 这样 相同的值 x ^ x = 0 剩下的一个值就是题目中所寻找的Single Number

class Solution {
public:
    int singleNumber(vector& nums) {
        int res = 0;
        for(int i : nums){
            res ^= i;
        }
        return res;
    }
};

你可能感兴趣的:(136. Single Number)