Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fb1e1e8

Browse files
committedOct 12, 2021
refactor 169
1 parent 3640210 commit fb1e1e8

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
 

‎src/main/java/com/fishercoder/solutions/_169.java

+22
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,26 @@ public int majorityElement(int[] nums) {
4848
return res;
4949
}
5050
}
51+
52+
public static class Solution3 {
53+
/**
54+
* I'm glad to have come up with this idea myself on 10/12/2021.
55+
*/
56+
public int majorityElement(int[] nums) {
57+
int count = 1;
58+
int candidate = nums[0];
59+
for (int i = 1; i < nums.length; i++) {
60+
if (nums[i] != candidate) {
61+
count--;
62+
if (count < 0) {
63+
candidate = nums[i];
64+
count = 1;
65+
}
66+
} else {
67+
count++;
68+
}
69+
}
70+
return candidate;
71+
}
72+
}
5173
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._169;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _169Test {
10+
private static _169.Solution1 solution1;
11+
private static _169.Solution2 solution2;
12+
private static _169.Solution3 solution3;
13+
14+
@BeforeClass
15+
public static void setup() {
16+
solution1 = new _169.Solution1();
17+
solution2 = new _169.Solution2();
18+
solution3 = new _169.Solution3();
19+
}
20+
21+
@Test
22+
public void test1() {
23+
assertEquals(1, solution1.majorityElement(new int[]{1, 3, 1, 1, 4, 1, 1, 5, 1, 1, 6, 2, 2}));
24+
assertEquals(1, solution2.majorityElement(new int[]{1, 3, 1, 1, 4, 1, 1, 5, 1, 1, 6, 2, 2}));
25+
assertEquals(1, solution3.majorityElement(new int[]{1, 3, 1, 1, 4, 1, 1, 5, 1, 1, 6, 2, 2}));
26+
}
27+
28+
}

0 commit comments

Comments
 (0)
Failed to load comments.