There is an integer array, and we know that the number of occurrences of a number is more than half. Please use the complexity of O (n ).AlgorithmFind this number.
Method 1: Hash linked list
Method 2: Use two variables A and B, where a stores the number in an array and B is used to count. At the beginning, Class B is initialized to 0.
Traverse the array,
If B = 0, make a equal to the current number and B equal to 1;
If the current number is the same as that of a, B = B + 1;
If the current number is different from a, B = B-1.
At the end of the traversal, the number in a is the number to be searched.
The time complexity of this algorithm is O (n), and the space complexity is O (1 ).
C LanguageDescription:
- IntMain ()
- {
- IntI, A, B;
- IntA [10] = {1, 2, 3, 1, 2, 1, 6, 1 };
- A = A [5];
- B = 0;
- For(I = 0; I <10; I ++)
- If(B = 0)
- {
- A = A [I];
- B = 1;
- }ElseIf(A = A [I])
- B ++;
- ElseIf(! = A [I])
- B --;
- Printf ("% d", );
- Getchar ();
- Return0;
- }