The leetcode has the following two single number problems:
1. Assume that all elements in an integer array appearTwoOnly one element appears once. Find the element that appears once.
2. Assume that all the elements in an integer array appear3.Only one element appears once. Find the element that appears once.
Obviously, the only difference between the two problems is whether most elements appear twice or three times.
For problem 1: it is a good solution. Through the exclusive or operation, we can eliminate all elements that appear twice a ^ A = 0; in the end, only the element that appears once is 0 ^ B = B.
int singleNumber(int A[], int n){ int result=0; for(int i=0; i<n; i++) { result ^= A[i]; } return result;}
For Question 2: it is clear that we cannot continue to solve the problem by using an exclusive or bitwise operation. From the binary perspective, a number is nothing more than 0 and 1. If we only look at each bit, we add the content of this bit to the modulo 3, the resulting number is the value on this bit. With the value of a single number in each bit, the remaining number is displayed. In this case, we need an array of 32 to save this number. This space does not change with the increase of the N value of the array, so there is no problem from the perspective of space.
int singleNumber(int A[], int n){ int a[32] = {0}; int result=0; for(int i=0; i<32; i++) { for(int j=0; j<n; j++) { if((A[j]>>i)&0x1 == 1) a[i]++; } result |= ((a[i]%3)<<i); } return result;}
Of course, there is another easier solution to this problem after you click the open link.
Single Number Problems