Number of occurrences more than half in an array

Source: Internet
Author: User

Title: There is a number in the array that appears more than half the length of the array, please find this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which exceeds half the length of the array, the output is 2.

Ideas:

There is a number in the array that occurs more than half the length of the array, which means that it appears more often than all other numbers appear. So we can consider saving two values when iterating over an array: One is a number in an array, and the other is the number of times. When we traverse to the next number, the number is 1 if the next number is the same as the number we saved earlier, minus 1 if the next number differs from the number we saved earlier. If the number is zero, we need to save the next number and set the number to 1. Since the number we are looking for appears to be more than the sum of the number of other numbers appearing, the number to be searched is definitely the last number to be set at 1 o'clock.

int morethanhalfnum (int *numbers, int length) {if (Checkinvalidarray (numbers,length)) return 0;int result=numbers[0]; int times=1;for (int i=1; i<length; i++) {if (times==0) {Result=numbers[i];times=1;} else if (Result==numbers[i]) {times++;} else{times--;}} if (! Checkmorethanhalf (Numbers,length,result)) {result=0;} return result;} Check that the input parameters are reasonable bool G_inputinvalid=false;bool checkinvalidarray (int *numbers, int length) {g_inputinvalid=false;if ( numbers==null| | length<=0) {g_inputinvalid=true;} return g_inputinvalid;}  Check if the result is reasonable bool Checkmorethanhalf (int *numbers, int length, int number) {///count int times=0;for (int i=0; i<length; i++) {if (Numbers[i]==number) {times++;}} BOOL Ismorethanhalf=true;if (times*2<=length) {g_inputinvalid=true;ismorethanhalf=false;} return ismorethanhalf;}


Number of occurrences more than half in an array

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.