# [LeetCode] Array Nesting 数组嵌套

A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0, N - 1].

Sets S[K] for 0 <= K < N are defined as follows:

S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }.

Sets S[K] are finite for each K and should NOT contain duplicates.

Write a function that given an array A consisting of N integers, return the size of the largest set S[K] for this array.

Example 1:

Input: A = [5,4,0,3,1,6,2]
Output: 4
Explanation:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

Note:

1. N is an integer within the range [1, 20,000].
2. The elements of A are all distinct.
3. Each element of array A is an integer within the range [0, N-1].

public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), res = INT_MIN;
vector<bool> visited(n, false);
for (int i = 0; i < nums.size(); ++i) {
if (visited[nums[i]]) continue;
res = max(res, helper(nums, i, visited));
}
return res;
}
int helper(vector<int>& nums, int start, vector<bool>& visited) {
int i = start, cnt = 0;
while (cnt == 0 || i != start) {
visited[i] = true;
i = nums[i];
++cnt;
}
return cnt;
}
};

public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), res = INT_MIN;
vector<bool> visited(n, false);
for (int i = 0; i < n; ++i) {
if (visited[nums[i]]) continue;
int cnt = 0, j = i;
while(cnt == 0 || j != i) {
visited[j] = true;
j = nums[j];
++cnt;
}
res = max(res, cnt);
}
return res;
}
};

public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), res = 0;
for (int i = 0; i < n; ++i) {
int cnt = 1;
while (nums[i] != i && nums[i] != nums[nums[i]]) {
swap(nums[i], nums[nums[i]]);
++cnt;
}
res = max(res, cnt);
}
return res;
}
};

https://discuss.leetcode.com/topic/90537/this-is-actually-dfs

https://discuss.leetcode.com/topic/90538/c-java-clean-code-o-n

，如需转载请自行联系原博主。

|
1天前
|

C++的内置数组和STL array、STL vector
C++的内置数组和STL array、STL vector
|
10天前
|
C++ Python

10 1
|
11天前
|

【LeetCode刷题】二分查找：山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找：山脉数组的峰顶索引、寻找峰值
16 1
|
11天前
|

【经典LeetCode算法题目专栏分类】【第10期】排序问题、股票问题与TOP K问题：翻转对、买卖股票最佳时机、数组中第K个最大/最小元素
【经典LeetCode算法题目专栏分类】【第10期】排序问题、股票问题与TOP K问题：翻转对、买卖股票最佳时机、数组中第K个最大/最小元素
26 1
|
15天前
|

14 1
|
15天前
|

|
15天前
|

LeetCode题目89:格雷码 递归、迭代及位操作在数组合并中的应用
LeetCode题目89:格雷码 递归、迭代及位操作在数组合并中的应用
11 1
|
11天前
【LeetCode刷题】前缀和解决问题：742.寻找数组的中心下标、238.除自身以外数组的乘积
【LeetCode刷题】前缀和解决问题：742.寻找数组的中心下标、238.除自身以外数组的乘积
19 0
|
11天前
【LeetCode刷题】二分查找：寻找旋转排序数组中的最小值、点名
【LeetCode刷题】二分查找：寻找旋转排序数组中的最小值、点名
19 0
|
11天前
|

【经典LeetCode算法题目专栏分类】【第6期】二分查找系列：x的平方根、有效完全平方数、搜索二位矩阵、寻找旋转排序数组最小值
【经典LeetCode算法题目专栏分类】【第6期】二分查找系列：x的平方根、有效完全平方数、搜索二位矩阵、寻找旋转排序数组最小值
13 0