简体   繁体   中英

Elements in an array occurring more than size/2

I need help in one of the small arrays related question.

Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.

EXAMPLE 1:

Input:

 N = 3 A[] = {1,2,3}

Output:

 -1

Explanation:

Since, each element in {1,2,3} appears only once so there is no majority element.

EXAMPLE 2:

Input:

 N = 5 A[] = {3,1,3,3,2}

Output:

 3

Explanation:

Since, 3 is present more than N/2 times, so it is the majority element.

My code:

for(int i=0; i<size; i++) {
    int cn=1;
    for(int j=i+1; j<size; j++) {
        if(a[i]==a[j]) {
            cn++;
            if(cn>size/2) {
                return a[i];
            }
        }
        else {
            continue;
        }
    }
    return -1;

The above code takes two iteration.

The first iteration i=0; i<size; i++ i=0; i<size; i++ i=0; i<size; i++ is used to iterate through each element, similarly the second loop j=i+1; j<size; j++; j=i+1; j<size; j++; is used to compare the element at i'th position with the rest of the element in an array. While comparing the i'th element with the other elements in an arrays, if it's found that number of occurrence of i'th element is greater than the size/2 then it returns that particular element. If not, then it returns -1.

Although the above code satisfies multiple test cases, there's a single test case which it fails to satisfy.

Possibly your code doesn't work correctly for multiple test-cases (TCs).

The first test case where your code failed:

Input:

 1 15

Its Correct output is:

 15

And Your Code's output is:

 -1

Can anyone tell me the reason behind it? Is my logic incorrect, or am I missing something?

Your logic almost works, despite being suboptimal as mentioned by many in the comment.

The problem here is that your inner for loop will be completely skipped if size == 1 , which makes it return -1 when you only have one element in.

Without changing much of your logic, you can simply add a return before your for loop:

if(size == 1) return a[0];

One more thing is that you want to make sure your return -1 is after the outer for loop.

It might be a bad copy paste, but as current, it will just return -1 when the first item isn't the majority.


More on the optimized solution: Boyer–Moore majority vote algorithm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM