Fork me on GitHub

【LeetCode】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?

提示:

此题的主要是利用异或运算(xor)的特性:不同的输出1,相同的输出0。

例如:101 ^ 101 = 000, 111 ^ 000 = 111。

代码:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        vector<int>::iterator it;
        int result = 0;
        for (it = nums.begin(); it < nums.end(); ++it) {
            result ^= (*it);
        }
        return result;
    }
};
posted @ 2015-08-17 14:22  __Neo  阅读(105)  评论(0编辑  收藏  举报