Skip to content

Create BoyerMooreVoting.java #386

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Coding/Java/BoyerMooreVoting.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
public class BoyerMooreVoting {
public static int findMajorityElement(int[] nums) {
int candidate = 0;
int count = 0;

for (int num : nums) {
if (count == 0) {
candidate = num;
count = 1;
} else if (candidate == num) {
count++;
} else {
count--;
}
}

// After the first pass, 'candidate' should contain the majority element
// Verify if it is indeed the majority element by counting its occurrences
count = 0;
for (int num : nums) {
if (num == candidate) {
count++;
}
}

if (count > nums.length / 2) {
return candidate;
} else {
return -1; // No majority element found
}
}

public static void main(String[] args) {
int[] nums = {3, 3, 4, 2, 4, 4, 2, 4, 4};
int result = findMajorityElement(nums);
if (result != -1) {
System.out.println("Majority element: " + result);
} else {
System.out.println("No majority element found");
}
}
}