A number in the array appears more than half the length of the array.

Source: Internet
Author: User

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"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.