索引从0
开始长度为N
的数组A
,包含0
到N - 1
的所有整数。找到最大的集合S
并返回其大小,其中 S[i] = {A[i], A[A[i]], A[A[A[i]]], ... }
且遵守以下的规则。
假设选择索引为i
的元素A[i]
为S
的第一个元素,S
的下一个元素应该是A[A[i]]
,之后是A[A[A[i]]]...
以此类推,不断添加直到S
出现重复的元素。
示例 1:
输入: A = [5,4,0,3,1,6,2] 输出: 4 解释: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. 其中一种最长的 S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
提示:
1 <= nums.length <= 105
0 <= nums[i] < nums.length
A
中不含有重复的元素。
方法一:图
嵌套数组最终一定会形成一个环,在枚举
时间复杂度
方法二:原地标记
由于
时间复杂度
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
n = len(nums)
vis = [False] * n
res = 0
for i in range(n):
if vis[i]:
continue
cur, m = nums[i], 1
vis[cur] = True
while nums[cur] != nums[i]:
cur = nums[cur]
m += 1
vis[cur] = True
res = max(res, m)
return res
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for i in range(n):
cnt = 0
while nums[i] != n:
j = nums[i]
nums[i] = n
i = j
cnt += 1
ans = max(ans, cnt)
return ans
class Solution {
public int arrayNesting(int[] nums) {
int n = nums.length;
boolean[] vis = new boolean[n];
int res = 0;
for (int i = 0; i < n; i++) {
if (vis[i]) {
continue;
}
int cur = nums[i], m = 1;
vis[cur] = true;
while (nums[cur] != nums[i]) {
cur = nums[cur];
m++;
vis[cur] = true;
}
res = Math.max(res, m);
}
return res;
}
}
class Solution {
public int arrayNesting(int[] nums) {
int ans = 0, n = nums.length;
for (int i = 0; i < n; ++i) {
int cnt = 0;
int j = i;
while (nums[j] < n) {
int k = nums[j];
nums[j] = n;
j = k;
++cnt;
}
ans = Math.max(ans, cnt);
}
return ans;
}
}
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size();
vector<bool> vis(n);
int res = 0;
for (int i = 0; i < n; ++i) {
if (vis[i]) continue;
int cur = nums[i], m = 1;
vis[cur] = true;
while (nums[cur] != nums[i]) {
cur = nums[cur];
++m;
vis[cur] = true;
}
res = max(res, m);
}
return res;
}
};
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int ans = 0, n = nums.size();
for (int i = 0; i < n; ++i)
{
int cnt = 0;
int j = i;
while (nums[j] < n)
{
int k = nums[j];
nums[j] = n;
j = k;
++cnt;
}
ans = max(ans, cnt);
}
return ans;
}
};
func arrayNesting(nums []int) int {
n := len(nums)
vis := make([]bool, n)
ans := 0
for i := 0; i < n; i++ {
if vis[i] {
continue
}
cur, m := nums[i], 1
vis[cur] = true
for nums[cur] != nums[i] {
cur = nums[cur]
m++
vis[cur] = true
}
if m > ans {
ans = m
}
}
return ans
}
func arrayNesting(nums []int) int {
ans, n := 0, len(nums)
for i := range nums {
cnt, j := 0, i
for nums[j] != n {
k := nums[j]
nums[j] = n
j = k
cnt++
}
if ans < cnt {
ans = cnt
}
}
return ans
}