Given an array of integers, every element appears three times must t for one. Find that single one.
Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?
The question is clear, with emphasis on the extra space of Linear Time and constants. Single number I refers to the difference or, finally, the answer. But here there are three, what should I do?
When there are three times, if we still start with bitwise operations, what are the features? Set the unique number to X. The feature is that it is measured in 32 bits of the int type. Assume that X is 0 on this bit, then it should be that the number of occurrences of the bit 1 is a multiple of 3, and if it is 1, it should be 1 of the occurrence of the 3N + 1. According to this feature, to calculate the unique data;
Set three intors, one, two, and three. Here, a value of 0 is displayed. Once it is set to 0, twice, once it is set to 1, and once it is set to 1, the high value here exists in two, and the low value exists in one, perform operations according to different States. At the same time, 0 is cleared for 1. here, one represents the low-level count of each bit, and two represents the High-Level count of each bit;
Public: int singlenumber (int A [], int N) {int one = 0, two = 0, three = 0; For (INT I = 0; I <N; I ++) {two | = one & A [I]; // be careful one ^ = A [I]; three = one & two; one & = ~ Three; two & = ~ Three;} return one ;}
Here, be careful two can use exclusive or, because it is impossible for one two to have the same bit at the same time, so the exclusive or the same, but logically, it should be optional or, better represents the meaning of this algorithm;