Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitfb1e1e8

Browse files
refactor 169
1 parent3640210 commitfb1e1e8

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,26 @@ public int majorityElement(int[] nums) {
4848
returnres;
4949
}
5050
}
51+
52+
publicstaticclassSolution3 {
53+
/**
54+
* I'm glad to have come up with this idea myself on 10/12/2021.
55+
*/
56+
publicintmajorityElement(int[]nums) {
57+
intcount =1;
58+
intcandidate =nums[0];
59+
for (inti =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+
returncandidate;
71+
}
72+
}
5173
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
packagecom.fishercoder;
2+
3+
importcom.fishercoder.solutions._169;
4+
importorg.junit.BeforeClass;
5+
importorg.junit.Test;
6+
7+
importstaticorg.junit.Assert.assertEquals;
8+
9+
publicclass_169Test {
10+
privatestatic_169.Solution1solution1;
11+
privatestatic_169.Solution2solution2;
12+
privatestatic_169.Solution3solution3;
13+
14+
@BeforeClass
15+
publicstaticvoidsetup() {
16+
solution1 =new_169.Solution1();
17+
solution2 =new_169.Solution2();
18+
solution3 =new_169.Solution3();
19+
}
20+
21+
@Test
22+
publicvoidtest1() {
23+
assertEquals(1,solution1.majorityElement(newint[]{1,3,1,1,4,1,1,5,1,1,6,2,2}));
24+
assertEquals(1,solution2.majorityElement(newint[]{1,3,1,1,4,1,1,5,1,1,6,2,2}));
25+
assertEquals(1,solution3.majorityElement(newint[]{1,3,1,1,4,1,1,5,1,1,6,2,2}));
26+
}
27+
28+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp