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.
算法思路
(1)题目其实非常简单,其实就是用深度优先搜索就可以了。比如先设置index=A[i], 然后设置index=A[index],直到index再次等于A[i]。
(2)但其实一开始我并没有,而是发现超时了。然后我就再看了一下例题,发现了一个规律。
S[0]={A[0]=5, A[5]=6, A[6]=2, A[2]=0};
S[2]={A[2]=0,A[0]=5, A[5]=6, A[6]=2};
S[5]={A[5]=6, A[6]=2,A[2]=0,A[0]=5};
S[6]={A[6]=2, A[2]=0,A[0]=5, A[5]=6};
其中S[0],S[2],S[5]与S[6]包含的元素相同。也就是说,并不用每一个元素都变量,也就是并不用对数组中的每一个元素都执行dfs,当一个元素在之前的dfs被访问过,以后也就不用再访问了。也就是把原来代码中的一句注释掉即可。
算法代码
class Solution {
private:
bool flag[30000];
int res;
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size();
for(int i = 0 ; i < n; i++)
flag[i] = false;
res = 0;
for (int i = 0; i < n; ++i)
{
dfs(nums,i,n,0);
}
return res;
}
void dfs(vector<int>& nums, int index, int n, int d){
if(index >= 0 && index < n && !flag[index]){
flag[index] = true;
dfs(nums,nums[index],n,d + 1);
//flag[index] = false;
}
else{
if(res < d){
res = d;
}
}
}
};