-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0697-degree-of-an-array.js
39 lines (35 loc) · 1018 Bytes
/
0697-degree-of-an-array.js
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
/**
* 697. Degree of an Array
* https://leetcode.com/problems/degree-of-an-array/
* Difficulty: Easy
*
* 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.
*
* Your task is to find the smallest possible length of a (contiguous) subarray of
* nums, that has the same degree as nums.
*/
/**
* @param {number[]} nums
* @return {number}
*/
var findShortestSubArray = function(nums) {
const map = new Map();
nums.forEach((key, index) => {
if (!map.has(key)) {
map.set(key, { start: index, end: index, count: 1 });
}
const { start, end, count } = map.get(key);
map.set(key, { start, end: index, count: count + 1 });
});
let max = 0;
let result = Infinity;
Array.from(map).forEach(([_, { start, end, count }]) => {
const min = (end - start) + 1;
if (count > max || (min < result && count === max)) {
result = min;
max = count;
}
});
return result;
};