首页 > 代码库 > [LeetCode] Single Number

[LeetCode] 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?

 分析:用下列multiset时间复杂度O(n),空间复杂度O(n),因为额外用的multiset的大小和数组大小相同。

#include<set>
using namespace std;

class Solution {
public:
    int singleNumber(int A[], int n) {
        multiset<int> ms;
        for(int i=0;i<n;i++)
            ms.insert(A[i]);
        for(int i = 0;i<n;i++)
        {
          int num = ms.count(A[i]);
          if(num == 1)
              return A[i];
        }
    }
};

 分析:用“异或的方法”,原理是:两个相同的数异或等于0,0和任意数A异或等于A。

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