File tree 2 files changed +35
-0
lines changed
2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change 21
21
451|[ Sort Characters By Frequency] ( ./0451-sort-characters-by-frequency.js ) |Medium|
22
22
459|[ Repeated Substring Pattern] ( ./0459-repeated-substring-pattern.js ) |Easy|
23
23
541|[ Reverse String II] ( ./0541-reverse-string-ii.js ) |Easy|
24
+ 565|[ Array Nesting] ( ./0565-array-nesting.js ) |Medium|
24
25
606|[ Construct String from Binary Tree] ( ./0606-construct-string-from-binary-tree.js ) |Easy|
25
26
617|[ Merge Two Binary Trees] ( ./0617-merge-two-binary-trees.js ) |Easy|
26
27
648|[ Replace Words] ( ./0648-replace-words.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments