single-number

来源:互联网 发布:centos装nginx 编辑:程序博客网 时间:2024/05/22 12:07

题目描述

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?

解决思路

异或运算的巧妙使用,由于两个相等的数异或值为0,所以将数组所有值相异或便得到答案

代码:

class Solution {public:    int singleNumber(int A[], int n) {        int res = 0;        int i;        for (i = 0; i < n; i++)             res ^= A[i];        return res;    }};
0 0