【Leetcode】【Medium】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?

 

解题:

此题可直接运用异或运算的性质:N^A^A = N

代码:

1 class Solution {
2 public:
3     int singleNumber(int A[], int n) {
4         for (int i = 1; i < n; ++i) 
5             A[0] ^= A[i];
6         return A[0];
7     }
8 };

 

但是在leetcode网站性能分析中,异或运算(19ms)不是最快的,不知道还有没有其他算法可以达到10ms以下。

posted @ 2015-01-15 22:19  胡潇  阅读(126)  评论(0编辑  收藏  举报