Description: Given An array of integers, every element appears twice except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
The topic requires O (n) time complexity, O (1) space complexity.
Idea 1: The initial use of brute force search, traversing the array, found that two elements are equal, then the two elements of the flag position is 1, and finally return the element with the flag bit 0. Time complexity O (n^2) no ac,status:time Limit exceed
1 classSolution {2 Public:3 intSinglenumber (intA[],intN) {4 5Vector <int> Flag (N,0);6 7 for(inti =0; I < n; i++) {8 if(Flag[i] = =1)9 Continue;Ten Else { One for(intj = i +1; J < N; J + +) { A if(A[i] = =A[j]) { -Flag[i] =1; -FLAG[J] =1; the } - } - } - } + - for(inti =0; I < n; i++) { + if(Flag[i] = =0) A returnA[i]; at } - } -};
Idea 2: Use XOR or operation. Nature of XOR 1: Commutative law a ^ b = b ^ A, nature 2:0 ^ a = A. Therefore, the Exchange law can be used to imagine the array of the same elements are all adjacent, so that all the elements in turn XOR or operation, the same element is different or 0, the final remaining element is a single number. Time complexity O (n), Spatial complexity O (1)
1 classSolution {2 Public:3 intSinglenumber (intA[],intN) {4 5 //XOR or6 intElem =0;7 for(inti =0; I < n; i++) {8Elem = elem ^A[i];9 }Ten One returnElem; A } -};
Leetcode Problem 136:single Number