Skip to content

Commit 1d91436

Browse files
Added MooreVoting.java new Algorithm Fixes TheAlgorithms#5654
1 parent b54cc21 commit 1d91436

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.util.Arrays;
2+
3+
public class MajorityElement {
4+
public static int findMajorityElement(int[] nums) {
5+
int candidate = nums[0];
6+
int count = 1;
7+
8+
for (int i = 1; i < nums.length; i++) {
9+
if (count == 0)
10+
{
11+
candidate = nums[i];
12+
count = 1;
13+
} else if (nums[i] == candidate)
14+
{
15+
count++;
16+
} else
17+
{
18+
count--;
19+
20+
}
21+
}
22+
23+
// Verify if candidate is the majority element
24+
count = 0;
25+
for (int num : nums)
26+
{
27+
if (num == candidate)
28+
{
29+
count++;
30+
}
31+
}
32+
33+
if (count > nums.length / 2)
34+
{
35+
return candidate;
36+
} else
37+
{
38+
return -1; // No majority element found
39+
}
40+
}
41+
42+
public static void main(String[] args) {
43+
int[] nums = {2, 1, 2, 1, 2, 2, 1};
44+
int majorityElement = findMajorityElement(nums);
45+
46+
if (majorityElement != -1)
47+
{
48+
System.out.println("Majority element: " + majorityElement);
49+
} else
50+
{
51+
System.out.println("No majority element found");
52+
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)