Created
July 31, 2014 05:29
-
-
Save xiren-wang/3a0fc1e9f158ec2f8ca9 to your computer and use it in GitHub Desktop.
single number inside an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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? | |
*/ | |
int singleNumber(int A[], int n) { | |
if (n <= 0) | |
return -1; | |
int a0 = A[0]; | |
for(int i=1; i<n; i++) | |
a0 ^= A[i]; | |
return a0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have to first check n <=0, otherwise a0=A[0] may crash for illegal memory access