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 c610034

Browse files
author
Sandy
authored
Merge pull request #195 from openset/develop
Add: Degree of an Array
2 parents 0cad587 + e17c85b commit c610034

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,20 @@
11
package degree_of_an_array
2+
3+
func findShortestSubArray(nums []int) int {
4+
m, ans := make(map[int]int), 0
5+
first, max := make(map[int]int), 0
6+
for i, v := range nums {
7+
m[v]++
8+
if first[v] == 0 {
9+
first[v] = i + 1
10+
}
11+
if m[v] >= max {
12+
t := i - first[v] + 2
13+
if m[v] > max || (m[v] == max && t < ans) {
14+
ans = t
15+
}
16+
max = m[v]
17+
}
18+
}
19+
return ans
20+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package degree_of_an_array
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestFindShortestSubArray(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{1, 2, 2, 3, 1},
14+
expected: 2,
15+
},
16+
{
17+
input: []int{1, 2, 2, 3, 1, 4, 2},
18+
expected: 6,
19+
},
20+
{
21+
input: []int{1},
22+
expected: 1,
23+
},
24+
{
25+
input: []int{2, 1, 1, 2, 1, 3, 3, 3, 1, 3, 1, 3, 2},
26+
expected: 7,
27+
},
28+
{
29+
input: []int{1, 2, 2, 3, 1},
30+
expected: 2,
31+
},
32+
}
33+
for _, tc := range tests {
34+
output := findShortestSubArray(tc.input)
35+
if output != tc.expected {
36+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
(0)

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