Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 6e3a52c

Browse files
aQuaaQua
aQua
authored and
aQua
committed
697 accepted. 108ms > 55ms
1 parent 97fa658 commit 6e3a52c

File tree

3 files changed

+110
-0
lines changed

3 files changed

+110
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# [697. Degree of an Array](https://leetcode.com/problems/degree-of-an-array/)
2+
3+
## 题目
4+
5+
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
6+
7+
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
8+
9+
Example 1:
10+
11+
```text
12+
Input: [1, 2, 2, 3, 1]
13+
Output: 2
14+
Explanation:
15+
The input array has a degree of 2 because both elements 1 and 2 appear twice.
16+
Of the subarrays that have the same degree:
17+
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
18+
The shortest length is 2. So return 2.
19+
```
20+
21+
Example 2:
22+
23+
```text
24+
Input: [1,2,2,3,1,4,2]
25+
Output: 6
26+
```
27+
28+
Note:
29+
30+
- nums.length will be between 1 and 50,000.
31+
- nums[i] will be an integer between 0 and 49,999.
32+
33+
## 解题思路
34+
35+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package Problem0697
2+
3+
func findShortestSubArray(nums []int) int {
4+
size := len(nums)
5+
if size < 2 {
6+
return size
7+
}
8+
9+
first := make(map[int]int, size)
10+
count := make(map[int]int, size)
11+
maxCount := 1
12+
minLen := size
13+
for i, n := range nums {
14+
count[n]++
15+
if count[n] == 1 {
16+
first[n] = i
17+
} else {
18+
l := i - first[n] + 1
19+
if maxCount < count[n] ||
20+
(maxCount == count[n] && minLen > l) {
21+
maxCount = count[n]
22+
minLen = l
23+
}
24+
}
25+
}
26+
27+
if len(count) == size {
28+
return 1
29+
}
30+
return minLen
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package Problem0697
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
// tcs is testcase slice
11+
var tcs = []struct {
12+
nums []int
13+
ans int
14+
}{
15+
16+
{
17+
[]int{1, 2, 2, 3, 1},
18+
2,
19+
},
20+
21+
{
22+
[]int{1, 2, 2, 3, 1, 4, 2},
23+
6,
24+
},
25+
26+
// 可以有多个 testcase
27+
}
28+
29+
func Test_fn(t *testing.T) {
30+
ast := assert.New(t)
31+
32+
for _, tc := range tcs {
33+
fmt.Printf("~~%v~~\n", tc)
34+
ast.Equal(tc.ans, findShortestSubArray(tc.nums), "输入:%v", tc)
35+
}
36+
}
37+
38+
func Benchmark_fn(b *testing.B) {
39+
for i := 0; i < b.N; i++ {
40+
for _, tc := range tcs {
41+
findShortestSubArray(tc.nums)
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)