Title: Suppose a machine stores only a record labeled ID, assuming that each of the data holds 2 backups, so that 2 machines store the same data. Where ID is an integer:
Question 1, at a certain time, if you get a list of data file IDs. Can you quickly find an ID that appears only once in this table? That is, quickly identify the data ID of the failed machine store.
Question 2, if there are two machines crash. (assuming that two backups of the same data are not lost at the same time, that is, two unequal IDs are missing from the list)
Solution One: Use XOR or operation: All the IDs in the list are different or, and the resulting value is the ID.
The use of a different or operation can be
X^x=0 x^y=z x^0=x
As an example:
For example, ID 2 1 2 3 1 to find the ID of 3
The binary of 2 is the binary of the 010,1 is 001
The binary of 3 is 011 2⊕1 = 010⊕001= 011
011⊕2 = 011⊕010=001=1 (2⊕1⊕2 = 1)
1⊕3 = 001⊕011=010 010⊕001=011 = 3
The final result is still the number that appears only once.
The time complexity is O (N), and the space complexity is O (1). In time and space, the basic has reached the optimal.
disadvantage: The premise is that only one ID appears once, if many times, it is not appropriate
Solution two: Using invariant
Idea: Here, the sum of all the IDs is one invariant, and the remaining IDs are now added. The difference between the sum of all IDs and the remaining IDs is the ID that is being asked.
Complexity of Time: O (N) time, Space complexity O (1)
Topics after this lesson:
Give you a messy playing card (excluding the king of the size), arbitrarily draw a card from it, how to use the simplest way to know that out of the 1~13 of the one. (not required to know the color)
methods: Using invariant
Calculate all cards in advance and (1+...+13) x 4 = 364
Then subtract the number of cards left, and finally get the one you pulled out!