Skip to content

Commit e3806fe

Browse files
AdiAdi
authored andcommitted
Add JUnit test for MajorityElement
1 parent d0d4b3c commit e3806fe

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/searching/MajorityElement.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package searching;
2+
3+
/**
4+
* LeetCode Problem 169: Majority Element
5+
* Boyer-Moore Voting Algorithm
6+
*/
7+
public class MajorityElement {
8+
public static int findMajority(int[] nums) {
9+
int count = 0;
10+
Integer candidate = null;
11+
12+
for (int num : nums) {
13+
if (count == 0) {
14+
candidate = num;
15+
}
16+
count += (num == candidate) ? 1 : -1;
17+
}
18+
19+
return candidate;
20+
}
21+
22+
public static void main(String[] args) {
23+
int[] nums = {2, 2, 1, 1, 1, 2, 2};
24+
System.out.println("Majority element: " + findMajority(nums));
25+
}
26+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package search;
2+
3+
import searching.MajorityElement;
4+
import org.junit.Test;
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class MajorityElementTest {
8+
9+
@Test
10+
public void testMajorityElement1() {
11+
int[] nums = {3, 3, 4, 2, 3, 3, 3};
12+
assertEquals(3, MajorityElement.findMajority(nums));
13+
}
14+
15+
@Test
16+
public void testMajorityElement2() {
17+
int[] nums = {2, 2, 1, 1, 2, 2};
18+
assertEquals(2, MajorityElement.findMajority(nums));
19+
}
20+
21+
@Test
22+
public void testMajorityElementSingle() {
23+
int[] nums = {1};
24+
assertEquals(1, MajorityElement.findMajority(nums));
25+
}
26+
}

0 commit comments

Comments
 (0)