This question is actually not difficult. It can be answered in a very stupid way, But it wastes the time and space of the program and finds a good idea from the Internet.
A number appears more than half the length of the array. That is, a number appears more than the sum of all other numbers. When traversing the array, save the connected values. One is the number in the array, and the other is the number of occurrences. When traversing to a number, if the number is the same as the previously saved number, add one to the number, if the number is different from the previously saved number, the number is reduced by one. If the number is zero, the next array element is traversed and the number is set to one. The number you are looking for must be the number corresponding to the last time you set the number to 1.
# Include <iostream>
Using namespace std;
Bool g_bInputInvalid = false;
Int MoreThanHalfNum (int * numbers, unsigned int length)
{
If (numbers = NULL & length = 0)
{
G_bInputInvalid = true;
Return 0;
}
G_bInputInvalid = false;
Int result = numbers [0];
Int times = 1;
For (int I = 1; I <length; ++ I)
{
If (times = 0)
{Result = numbers [I];
Times = 1;
}
Else if (numbers [I] = result)
Times ++;
Else
Times --;
}
// Verify whether the input is valid
Times = 0;
For (int I = 0; I <length; ++ I)
{
If (numbers [I] = result)
Times ++;
}
If (times * 2 <= length)
{
G_bInputInvalid = true;
Result = 0;
}
Return result;
}
Void main ()
{
Int a [] = {1, 2, 3, 4, 5, 2, 2 };
Int re = MoreThanHalfNum (a, 9 );
Cout <re;
}
Author: "cainiao changes"