The meaning of this topic is probably this:
Give me an array of integers with elements that appear two times, but one element appears only once, and you have to find the element that appears only once. It also requires that the time complexity of the algorithm be linear, i.e. O (N).
At first I thought for a long time, never found a way. If the element type is not defined as Integer, it is not possible to find the element that appears only once in linear time. So I think the breakout point should be that the element type is integer.
Why can an integer achieve a result within a linear time? I opened the label that the title belongs to, "bit manipulation"-bit operation. It seems like all of a sudden, bit manipulation is a magical thing, and it hides the philosophy of Boolean algebra behind it. Remember in the beginning to learn programming, exchange A, b two number can be used three times different or complete, then always think why.
So the breach of this topic has been found, the common bit operation has a "mask", and 1 for & operation, the result is unchanged, and 0 for the & operation, the position is 0. The bit operation to be used for this problem is "XOR", "XOR" has two features:
1, a number with any one of the different or two times, the result is the original number.
2, a number and 0 are different or, the result is the original number.
Ah! So it looks like the answer to this question is out!
1 classSolution {2 Public:3 intSinglenumber (vector<int>&nums) {4 intresult =0;5 for(Auto first = Nums.cbegin (); First! = Nums.cend (); first++) {6Result ^= *First ;7 }8 returnresult;9 }Ten};
I also want to brush leetcode--1, single number