[Problem]
Compile the following functions: int majorityelement (INT array [], int N );
This function returns most elements in the array. A majority element is a value that accounts for an absolute majority (at least 51%. If most elements do not exist, the constant nomajorityelement is returned. This function must meet the following conditions:
1. It must be run at O (n) time.
2. The additional space of O (1) must be used. In other words, individual temporary variables can be used instead of any temporary array. It cannot be solved by recursion, because as the number of recursive layers deepens, space is required to store stack frames.
3. The value of any element in the array cannot be changed.
[Code]
#include <stdio.h>void MajorityElement(int array[], int n){int majority, i, count;majority = array[0];count = 1;for(i = 1; i < n; i++){if(majority != array[i]){if(count == 0){majority = array[i];count++;}else{count--;}}else{count++;}}if(count > 0)printf("MajorityElement: %d\n", majority);elseprintf("NoMajorityElement\n");}main(){int array[5] = {1, 2, 1, 2, 3};MajorityElement(array, 5);}