Leetcode notes: Single Number, leetcodesingle
I. Description
Ii. Solutions
As mentioned in the question, each number in an array appears only once, and the other number appears twice to find this special number.
This question requires time and space. In the face of this situation, it generally implies a very lightweight and simple method for solving. In some scenarios, using basic logical operations is a good choice. I simply wrote it myself, and then referred to some online solutions, basically using the exclusive or operation (XOR ),Any number is equal to or equal to 0, while any number is equal to or equal to itself..
In C/C ++, the bitwise XOR or operator is: "^"
Based on the above rules, we can compare the elements of the entire array by bit or, and finally return the number that appears only once.
Iii. Sample Code
// Time complexity O (n), space complexity O (1) class Solution {public: int FindSingleNumber (int A [], int n) {int x = 0; for (size_t I = 0; I <n; ++ I) x ^ = A [I]; // XOR return x ;}};
Iv. Summary
This topic uses an exclusive or in bool operations. There are no major difficulties in addition, and I wonder if there are more efficient algorithms.
Because we use exclusive or, combined with the summary of relevant online blog posts, here we record the nature and common usage of exclusive or operations. In fact, these properties are easy to verify:
The result of a Number is different from the result of a self-calculation.0
;
And0
Make an exception or keep the original value unchanged, and1
Returns the opposite value of the original value;
Ifa1^a2^a3^…^an
The result is1
, Indicatesa1
Toan
Medium1
The number isOddOtherwiseEven. This property can be used for parity;
x^x^y == y
The derivation is simple:x^x == 0
, And0^y == y
. This property can be used to realize the exchange of two numbers without the use of intermediate variables to exchange two numbers, such as the following swap function, to exchange the values of a and B:
void swap(int &a,int &b){ a ^= b; b ^= a; a ^= b;}
However, this method is not without a vulnerability.. If you entera
Andb
The result is not what we want because the values are equal:
a ^= a;a ^= a;a ^= a;
The difference or result is naturally0
.
Therefore, this error can be avoided by changing the value exchange function to the following format:
Void swap (int & a, int & B) {if (a = B) return; // prevent & a, & B points to the same address a ^ = B; B ^ = a; a ^ = B ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.