Topic:
Given An array of numbers nums
, in which exactly-elements appear only once and all the other elements appear exactly Twice. Find the elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. The above example, is
[5, 3]
also correct.
- Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?
Links: http://leetcode.com/problems/single-number-iii/
Exercises
Last night stuck to the present. But last night before going to bed Google a bit, see a few articles later only understand. It is still necessary to strengthen bit manipulation. In the final analysis, the digital circuit did not learn-_____ at university-!! I'm overwhelmed with my undergraduate career ... Omit 100 million words.
Here we are primarily different or all numbers, get a^b, because A and B are not equal, so there is at least one bit bit in a^b k,k = 1. Then we can use this K-bit to judge, because A and B is only a number of k-bit = 1, we have all the input array K-bit 1 of the number is different or, we can find A and B in the K-bit 1, and then use this number A and a^b, we also obtained B.
Time Complexity-o (n), Space complexity-o (1).
Public classSolution { Public int[] Singlenumber (int[] nums) { int[] res = {-1,-1}; if(Nums = =NULL|| Nums.length = = 0) { returnRes; } intA_xor_b = 0; for(inti = 0; i < nums.length; i++) {//Find a ^ bA_xor_b ^=Nums[i]; } intk = 0;//find one bit in a^b = = 1 for(inti = 0; I < 31; i++) {//that means only one num in a, B have 1 on kth bit if(((A_xor_b >> i) & 1) = = 1) {k=i; Break; } } intA = 0; for(inti = 0; i < nums.length; i++) {//since only one num in a, B have 1 on kth bit if(((nums[i) >> k) & 1) = = 1) {//we can XOR all nums have 1 on kth bitA ^= nums[i];//duplicate nums is evened out } } intb = a ^A_xor_b; res[0] =A; res[1] =b; returnRes; }}
Off Topic:
In fact, when the undergraduate course, the school set up a very good curriculum, the teacher also strive to be pragmatic, all blame oneself did not put the mind on the study. Although the major is EE, but like what the base sort, Huffman code, run-length code, image processing and other things, teachers are also many introduced. There is a lot of information, and homework and exams are difficult. It really takes four years to learn the truth, it is not now a young age still in the brush problem. The past is over, then make a good effort.
Reference:
Https://groups.google.com/forum/#!topic/pongba/9KCA7b484OE
Https://groups.google.com/forum/#!topic/pongba/drV6dytcoJE
http://www.matrix67.com/blog/archives/511
260. Single number III