-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
67 lines (61 loc) · 1.13 KB
/
Solution.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
func findShortestSubArray(nums []int) (ans int) {
ans = 50000
numsMap := make(map[int]int, len(nums))
for _, num := range nums {
numsMap[num]++
}
var maxDegree int
for _, num := range numsMap {
maxDegree = max(num, maxDegree)
}
degreeNums := getMaxDegreeElem(maxDegree, numsMap)
for _, num := range degreeNums {
f := findSubArray(num, nums)
ans = min(ans, f)
}
return
}
func findSubArray(target int, nums []int) int {
start := getStartIdx(target, nums)
end := getEndIdx(target, nums)
return (end - start) + 1
}
func getStartIdx(target int, nums []int) (start int) {
for idx, num := range nums {
if num == target {
start = idx
break
}
}
return start
}
func getEndIdx(target int, nums []int) (end int) {
for i := len(nums) - 1; i > 0; i-- {
if nums[i] == target {
end = i
break
}
}
return
}
func getMaxDegreeElem(maxDegree int, numsMap map[int]int) []int {
var ans []int
for key, value := range numsMap {
if value == maxDegree {
ans = append(ans, key)
}
}
return ans
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
func max(a, b int) int {
if a > b {
return a
}
return b
}