If there is a number in the array that appears more than half the length of the array, 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. Output 0 If it does not exist.
C++:
1 classSolution {2 Public:3 intMorethanhalfnum_solution (vector<int>numbers) {4 if(Numbers.empty ())5 return 0 ;6 intMajority = numbers[0] ;7 intCNT =1 ;8 for(inti =1; I < numbers.size (); i++){9 if(CNT = =0){TenMajority =Numbers[i]; OneCNT =1 ; A}Else if(Numbers[i] = =majority) { -cnt++ ; -}Else{ thecnt-- ; - } - } -CNT =0 ; + for(inti =0; I < numbers.size (); i++){ - if(Numbers[i] = =majority) +cnt++ ; A } at if(CNT > Numbers.size ()/2) - returnmajority; - Else - return 0 ; - } -};
29 occurrences of more than half of the number in an array