Title: There is a number in the array that appears more than half the length of the array, please find this number.
Idea: First see this topic, an array of numbers appear more than half of the length of the array, it means that the number of occurrences more than the number of other numbers in the array number of occurrences of the sum. We can use two values to record when we traverse the array, one is the number of occurrences of the array count, a result that is used to save it, and we save the first number of the array as the result of the arr[0] as the results are compared with the next number, Count is 1, If the next number is the same as the previously saved number, count+1 is count-1 if it is different from the previously saved number. If the number is 0, we need to save its next number and set the number of times to 1. Since the number to be searched is more than half the length of the array, the last number set to 1 is the number we are looking for.
Code:
#include <iostream>using namespace std;int serach (int arr[],int len) {int count=1;int result=arr[0];for (int i=1;i& lt;len;i++) {if (count==0) {result=arr[i];count=1;} else if (result = = Arr[i]) count++;elsecount--;} return result;} int main () {int arr[]={1,2,3,2,2,2,5,4,2};int sz=sizeof (arr)/sizeof (arr[0]); int Ret=serach (ARR,SZ); Cout<<ret <<endl;return 0;}
Number of occurrences more than half in an array