LC.P565[数组嵌套]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int arrayNesting(int[] nums) {
int ans = 0;
for (int i = 0; i < nums.length; ++i) {
int cur = i, cnt = 0;
while (nums[cur] != -1) {
++cnt;
int t = cur;
cur = nums[cur];
nums[t] = -1;
}
ans = Math.max(ans, cnt);
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$