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

Commit 3553f52

Browse files
author
Sandy
authored
Merge pull request #108 from openset/develop
Add: majority_element
2 parents 3bff384 + ab175ba commit 3553f52

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,15 @@
11
package majority_element
2+
3+
func majorityElement(nums []int) int {
4+
count, ans := 1, nums[0]
5+
for _, n := range nums[1:] {
6+
if n != ans {
7+
count--
8+
}
9+
if count <= 0 {
10+
ans = n
11+
count = 1
12+
}
13+
}
14+
return ans
15+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package majority_element
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestMajorityElement(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{3, 2, 3},
14+
expected: 3,
15+
},
16+
{
17+
input: []int{2, 2, 1, 1, 1, 2, 2},
18+
expected: 2,
19+
},
20+
{
21+
input: []int{1},
22+
expected: 1,
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := majorityElement(tc.input)
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /