Topic
In an array of integers, except for two digits, the other numbers appear two times. Please find out the two numbers that appear only once. Requires time complexity O (n), Space complexity O (1)
Ideas
We know that if you change the number of two numbers in the title to one, the elements in the whole array are continuously different or the final number is the number that appears once, because the nature of the XOR is: the same is 0, the difference is 1, so there are any numbers or you are 0.
With two numbers, we can continue to the global XOR, the resulting number is necessarily not equal to 0, then that is, the binary is bound to have a 1, for example, the K-bit is 1, then according to the K-bit of all the elements is 1 divided into two sub-range, so that we in the two sub-interval according to the first method of
Code
public static void Gettwotimenumber (int [] num) {if (num = = NULL | | Num.length < 0) return; int sum = num[0];for (int i=1;i <num.length; i++) sum = Sum^num[i]; String sumbin = integer.tobinarystring (sum); Gets the final and binary int index = Sumbin.length ()-sumbin.lastindexof ("1")-1; Determine the last binary subscript//system.out.println (index); int RESULT1 = 0;int result2 = 0;for (int i = 0;i<num.length; i++) {if ((num[i ]>>index) & 1) ==1) result1 ^= num[i];elseresult2 ^= num[i];} System.out.println (result1+ "....." +RESULT2); }
Extended after reading this topic, I think again if the array appears once the number has 3, 4, 5 ..., that is how to find out the array of non-repeating numbers or to find the array of duplicate numbers.
There is a problem: an array of length N, the elements are 1~n, looking for duplicate numbers
There are such a few ideas: 1, first fast Platoon, and then determine whether the adjacent elements are the same, Time complexity O (NLOGN)
2, for example, the first position of the number is J, we will exchange J to the array labeled J, if a discovery has been exchanged, then this number repeats
3, the use of Java Bitset, each bit is 0 or 1, so similar to the above, for example, when the 5 is found, we will bitset the 5th position is true, the default is false, so when one time found that the bit is not set on has become true, it must have been repeated
Last recommended Some interview questions, turn to focus on a blog , the above summed up well.
Copyright NOTICE: This article is the original blogger articles, reproduced please indicate the source.
A number that appears only once in an array