Chapter One the music of the game quickly find out the faults in the machine quickly find the missing number

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.