The following two topics are derived from Leetcode:
1.Single number
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 general idea is to take each number in the array to traverse, if you can find it is not, if you cannot find the same number description to find the single value. It is clear that time complexity is O (n^n), the topic requires time complexity is linear, this method does not work, how to do the array only one time to find the results? The method is implemented using logical operators.
The principle is a^b=b^a;a^0=a;a^a=0. In this case only need to make each of the array of different or get the result is a single value, the same method is also suitable for the occurrence of odd number of values of the query, because the same number appears even after the difference or the result is 0, the occurrence of odd number of times the final form is 0^a=a,a is that the number of odd number of times, The code is as follows:
class solution { public : int Singlenumber (int a[], N) { int x = A[0 for (size_t i = 1 ; i < n; ++i) x ^= A[i]; return x;}};
2.Given an array of integers, every element appears three times except for one. Find the single one.
Note:your algorithm should has a linear runtime complexity. Could you implement it without using
Extra memory?
Here a number appears 1 times, the other number appears 3 times, can not use the above method, the problem-solving idea is to count each one, if a number appears 3 times, then the corresponding value modulo 3 result is 0, otherwise appear once the modulo 3 result for itself, so you can get the result, the code is as follows:
class Solution {
Public:
intSinglenumber (intA[],intN) { intbitarray[ +] = {0}; intres =0; for(inti =0; I < +; i++) { for(intj =0; J < n;j++) {Bitarray[i]+ = (a[j]>>i) &1; } Res|= (bitarray[i]%3) <<i; } returnRes;}
The use of logical operators in reducing time complexity