1
+ /*
2
+ Array Nesting
3
+ =============
4
+
5
+ You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
6
+
7
+ You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
8
+
9
+ The first element in s[k] starts with the selection of the element nums[k] of index = k.
10
+ The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
11
+ We stop adding right before a duplicate element occurs in s[k].
12
+ Return the longest length of a set s[k].
13
+
14
+ Example 1:
15
+ Input: nums = [5,4,0,3,1,6,2]
16
+ Output: 4
17
+ Explanation:
18
+ nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
19
+ One of the longest sets s[k]:
20
+ s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
21
+
22
+ Example 2:
23
+ Input: nums = [0,1,2]
24
+ Output: 1
25
+
26
+ Constraints:
27
+ 1 <= nums.length <= 105
28
+ 0 <= nums[i] < nums.length
29
+ All the values of nums are unique.
30
+ */
31
+
32
+ class Solution {
33
+ public:
34
+ int arrayNesting (vector<int >& A) {
35
+ int ans = 0 , n = A.size ();
36
+ vector<int > vis (n, 0 );
37
+
38
+ for (int i = 0 ; i < n; ++i) {
39
+
40
+ if (vis[i] == 0 ) {
41
+ int curr = i, count = 0 ;
42
+
43
+ while (vis[curr] == 0 ) {
44
+ vis[curr] = 1 ;
45
+ count++;
46
+ curr = A[curr];
47
+ }
48
+
49
+ ans = max (ans, count);
50
+ }
51
+
52
+ }
53
+
54
+ return ans;
55
+ }
56
+ };
0 commit comments