Skip to content

Commit be5d419

Browse files
committed
Add solution #697
1 parent 608c745 commit be5d419

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@
257257
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
258258
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
259259
695|[Max Area of Island](./0695-max-area-of-island.js)|Medium|
260+
697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy|
260261
700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy|
261262
701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium|
262263
704|[Binary Search](./0704-binary-search.js)|Easy|

solutions/0697-degree-of-an-array.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 697. Degree of an Array
3+
* https://leetcode.com/problems/degree-of-an-array/
4+
* Difficulty: Easy
5+
*
6+
* Given a non-empty array of non-negative integers nums, the degree of this array is
7+
* defined as the maximum frequency of any one of its elements.
8+
*
9+
* Your task is to find the smallest possible length of a (contiguous) subarray of
10+
* nums, that has the same degree as nums.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @return {number}
16+
*/
17+
var findShortestSubArray = function(nums) {
18+
const map = new Map();
19+
20+
nums.forEach((key, index) => {
21+
if (!map.has(key)) {
22+
map.set(key, { start: index, end: index, count: 1 });
23+
}
24+
const { start, end, count } = map.get(key);
25+
map.set(key, { start, end: index, count: count + 1 });
26+
});
27+
28+
let max = 0;
29+
let result = Infinity;
30+
Array.from(map).forEach(([_, { start, end, count }]) => {
31+
const min = (end - start) + 1;
32+
if (count > max || (min < result && count === max)) {
33+
result = min;
34+
max = count;
35+
}
36+
});
37+
38+
return result;
39+
};

0 commit comments

Comments
 (0)