Skip to content

Commit 0e292c9

Browse files
authored
Merge pull request #386 from Vanraj8169/patch-1
Create BoyerMooreVoting.java
2 parents deab9fe + b93e626 commit 0e292c9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Coding/Java/BoyerMooreVoting.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class BoyerMooreVoting {
2+
public static int findMajorityElement(int[] nums) {
3+
int candidate = 0;
4+
int count = 0;
5+
6+
for (int num : nums) {
7+
if (count == 0) {
8+
candidate = num;
9+
count = 1;
10+
} else if (candidate == num) {
11+
count++;
12+
} else {
13+
count--;
14+
}
15+
}
16+
17+
// After the first pass, 'candidate' should contain the majority element
18+
// Verify if it is indeed the majority element by counting its occurrences
19+
count = 0;
20+
for (int num : nums) {
21+
if (num == candidate) {
22+
count++;
23+
}
24+
}
25+
26+
if (count > nums.length / 2) {
27+
return candidate;
28+
} else {
29+
return -1; // No majority element found
30+
}
31+
}
32+
33+
public static void main(String[] args) {
34+
int[] nums = {3, 3, 4, 2, 4, 4, 2, 4, 4};
35+
int result = findMajorityElement(nums);
36+
if (result != -1) {
37+
System.out.println("Majority element: " + result);
38+
} else {
39+
System.out.println("No majority element found");
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)