Single Number [LEETCODE]

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?

 

========================================================================

Remember this property of XOR:

a ^ a = 0

0 ^ b =b

So all we need is to calculate XOR result in given array one by one.

Here's the code:

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         int result = 0;
 6         for (int i = 0; i < n ; i++) {
 7             result = result^A[i];
 8         }
 9         return result;
10         
11     }
12 };

 

posted @ 2013-10-13 11:50  昱铭  阅读(151)  评论(0)    收藏  举报