Skip to content

Conversation

@Aarav238
Copy link

Done using "Boyer-Moore Majority Voting Algorithm"

Done using "Boyer-Moore Majority Voting Algorithm"
@javadev
Copy link

javadev commented Sep 10, 2022

1 ms solution

public class Solution {
    public int majorityElement(int[] arr) {
        int count = 1;
        int majority = arr[0];
        // For Potential Majority Element
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] == majority) {
                count++;
            } else {
                if (count > 1) {
                    count--;
                } else {
                    majority = arr[i];
                }
            }
        }
        // For Confirmation
        count = 0;
        for (int j : arr) {
            if (j == majority) {
                count++;
            }
        }
        if (count >= (arr.length / 2) + 1) {
            return majority;
        } else {
            return -1;
        }
    }
}

@varunu28
Copy link
Owner

varunu28 commented Sep 11, 2022

There is no problem on LeetCode with name as Majority Elements. There is a problem named as Majority Element that is solved using the candidate voting algorithm. Code

Please have a look at the existing solutions before opening a PR. Thanks

@varunu28 varunu28 closed this Sep 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants