565. Array Nesting
Analysis
中午吃啥~—— [ummmm~]
A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], … } subjected to the rule below.
Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.
第一次做的时候很简单的想到两个循环(时间复杂度O(n*n)),最后发现大数据过不了,会TLE,然后看了一下大神们的做法,都只用了一个循环,也就是说之前已经遍历过得数据就不用再遍历一次了,因为这个每组数是一个循环,出现的点再考虑的话,无非是起点不一样,但是循环的数据数目还是一样的。如果出现的点再考虑的话,出现的结果和之前是一样的。
Implement
TLE solution
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int len = nums.size();
int res = INT_MIN;
for(int i=0; i<len; i++){
vector<int> visit(len, 0);
int cnt = 0;
int j = i;
while(1){
if(visit[nums[j]] == 1){
res = max(res, cnt);
break;
}
else{
cnt++;
visit[nums[j]] = 1;
j = nums[j];
}
}
}
return res;
}
};
AC solution
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int len = nums.size();
int res = INT_MIN;
vector<int> visit(len, 0);
for(int i=0; i<len; i++){
int cnt = 0;
int j = i;
while(1){
if(visit[nums[j]] == 1){
res = max(res, cnt);
break;
}
else{
cnt++;
visit[nums[j]] = 1;
j = nums[j];
}
}
}
return res;
}
};