leetcode136-Single Number
本文最后更新于:2024年7月6日 早上
Description
Given a non-empty 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?
Example 1:
1 |
|
Example 2:
1 |
|
Solution
First of all, need to recognize follow things:
XOR
XOR is a binary operation, it stands for “exclusive or”, that is to say the resulting bit evaluates to one if only exactly one of the bits is set.
This is its function table:
1
2
3
4
5
6a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0This operation is performed between every two corresponding bits of a number.
Example:
7 ^ 10
In binary:0111 ^ 1010
1
2
3
40111
^ 1010
======
1101 = 13Properties: The operation is commutative, associative and self-inverse.
XOR rules
- any number XOR to itself return 0
- any number XOR to 0 return itself
python code:
1 |
|
Golang code:
1 |
|