class Solution {
public int arrayNesting(int[] nums) {
int max=0;
for(int i=0;i<nums.length;i++){
boolean[] bool=new boolean[nums.length];
max=Math.max(max,dfs(bool,nums,i));
}
return max;
}
public static int dfs(boolean[] isSelect,int[] nums,int i){
//访问过的置true
isSelect[i]=true;
if(isSelect[nums[i]]){
return 1;
}else{
return 1+dfs(isSelect,nums,nums[i]);
}
}
}
开始没看题,当成一个树的dfs写的,遇到大数组会超时!
class Solution {
public int arrayNesting(int[] nums) {
//用同一个布尔数组标记
boolean[] bool=new boolean[nums.length];
int ans=0;
for(int i=0;i<nums.length;i++){
int cnt = 0;
//开始访问
while (!bool[i]) {
bool[i] = true;
i = nums[i];
++cnt;
}
ans = Math.max(ans, cnt);
}
return ans;
}
}
官方题解遍历时用同一个布尔数组标记,因为图可以形成一个环