Skip to content

Commit 387670d

Browse files
committed
feat: added code for Moore voting algorithm in java
1 parent 4c911e2 commit 387670d

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
public class MooreVoting {
2+
3+
public static Integer findMajorityElement(int[] nums) {
4+
// Phase 1: Find candidate
5+
int candidate = 0, count = 0;
6+
7+
for (int num : nums) {
8+
if (count == 0) {
9+
candidate = num;
10+
}
11+
if (num == candidate) {
12+
count++;
13+
} else {
14+
count--;
15+
}
16+
}
17+
18+
// Phase 2: Verify candidate
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 null; // No majority element
30+
}
31+
}
32+
33+
public static void main(String[] args) {
34+
int[] nums = {2, 2, 1, 1, 2, 2, 2};
35+
Integer majority = findMajorityElement(nums);
36+
37+
if (majority != null) {
38+
System.out.println("Majority Element: " + majority);
39+
} else {
40+
System.out.println("No Majority Element exists");
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)