Find the number with more than half of the occurrences in the array

Find the number with more than half of the occurrences in the array

Title description

Given an integer array arr, please print the number whose number of occurrences is greater than half. If there is no such number, please output -1.

Enter a description:

The input contains two lines, the first line contains an integer n (1 ≤ n ≤ 1 0 5) n(1 \leq n \leq 10^5)n(1n105 )represents the length of the array, the second line contains n numbers, representing the arrayarr (1 ≤ arri ≤ 1 0 9) arr(1 \leq arr_i \leq 10^9)arr(1arri109)

Output description:

Output an integer, which represents the number with more than half of the occurrences. If there is no such number, please output'-1'.

Example 1
enter
5
11 7 5 7 7
Output
7
Example 2
enter
4
2 2 3 3
Output
-1
Remarks:

Time complexity O (n) O(n)O ( n ) , additional space complexityO (1) O(1)O ( 1 )


answer:

The conventional solution can try to use a hash table to record the number of occurrences of each element, but the additional space complexity does not meet the requirements of the problem. Consider a relatively novel approach: every time we delete two different elements, if there is an element that appears more than half of the time in the sequence, then the element will be retained in the end. In this case, we can do it with only two variables (see the code for details).

Note: The last saved element is not necessarily the element with more than half of the occurrences. You also need to traverse the array and confirm it.

Code:
#include <cstdio>

using namespace std;

const int N = 100010;

int n;
int a[N];

int main(void) {
    
    
    scanf("%d", &n);
    int cand = 0;
    int times = 0;
    for ( int i = 0; i < n; ++i ) {
    
    
        scanf("%d", a + i);
        if ( !times ) {
    
    
            cand = a[i];
            times = 1;
        } else if ( a[i] == cand ) ++times;
        else --times;
    }
    if ( !cand ) return 0 * puts("-1");
    times = 0;
    int mid = n >> 1;
    for ( int i = 0; i < n && times <= mid; ++i ) times += ( a[i] == cand );
    if ( times > mid ) printf("%d\n", cand);
    else puts("-1");
    return 0;
}

Guess you like

Origin blog.csdn.net/MIC10086/article/details/109277514