Given a non-empty array of integers nums, every element appears
twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Given a non-empty array of integers nums, every element appears
twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Student
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Let's write code to find a single number from the array, we use the XOR technique to solve this problem in C#.
If I take the array [2, 2, 1].
Step-by-Step Execution
Initialization:
result = 0resultinitialized to0.First Iteration (
num = 2):result ^= 2which meansresult = result ^ 20 ^ 2 = 2(since0 XOR anythingequalsthat thing)result = 2Second Iteration (
num = 2):result ^= 2which meansresult = result ^ 22 ^ 2 = 0(sincea XOR a = 0)result = 0Third Iteration (
num = 1):result ^= 1which meansresult = result ^ 10 ^ 1 = 1(since0 XOR anythingequalsthat thing)result = 1Final Result
return result;1