Skip to content

Commit 0cea3a1

Browse files
committed
Add solution #565
1 parent 690e831 commit 0cea3a1

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium|
2222
459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy|
2323
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
24+
565|[Array Nesting](./0565-array-nesting.js)|Medium|
2425
606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy|
2526
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
2627
648|[Replace Words](./0648-replace-words.js)|Medium|

solutions/0565-array-nesting.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 565. Array Nesting
3+
* https://leetcode.com/problems/array-nesting/
4+
* Difficulty: Medium
5+
*
6+
* A zero-indexed array A of length N contains all integers from 0 to N-1.
7+
* Find and return the longest length of set S, where S[i] = {A[i],
8+
* A[A[i]], A[A[A[i]]], ... } subjected to the rule below.
9+
*
10+
* Suppose the first element in S starts with the selection of element
11+
* A[i] of index = i, the next element in S should be A[A[i]], and then
12+
* A[A[A[i]]]… By that analogy, we stop adding right before a duplicate
13+
* element occurs in S.
14+
*/
15+
16+
/**
17+
* @param {number[]} nums
18+
* @return {number}
19+
*/
20+
var arrayNesting = function(nums) {
21+
const history = new Set();
22+
let max = 0;
23+
for (let i = 0; i < nums.length; i++) {
24+
let count = 0;
25+
let j = i;
26+
while (!history.has(nums[j])) {
27+
j = nums[j];
28+
history.add(j);
29+
count++;
30+
}
31+
max = Math.max(max, count);
32+
}
33+
return max;
34+
};

0 commit comments

Comments
 (0)