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

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

异或运算实现。

posted @ 2014-03-20 12:22  小菜刷题史  阅读(131)  评论(0编辑  收藏  举报