Single Number

来源:互联网 发布:临汾直销软件 编辑:程序博客网 时间:2024/06/05 20:02

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,不同为1。所以所有元素异或一遍,最后剩下的一定是那个single number。

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


0 0