-
Notifications
You must be signed in to change notification settings - Fork 472
/
Copy pathBoyerMooreVoting.java
42 lines (38 loc) · 1.16 KB
/
BoyerMooreVoting.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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");
}
}
}