# [565. Array Nesting] C++ - Unordered_set or Vector or in-place change (O(1) space)

• ``````//O(1) space:
class Solution {
public:
int arrayNesting(vector<int>& nums) {
if(nums.empty()) return 0;
int res = 0;
for(int i = 0; i < nums.size(); ++i){
if(nums[i] == -1){
continue;
}
int tmp = 0;
int k = i;
while(nums[k] != -1){
tmp++;
int tmp2 = nums[k];
nums[k] = -1;
k = tmp2;

}
res = max(res, tmp);
}
return res;
}
};

//vector
class Solution {
public:
int arrayNesting(vector<int>& nums) {
if(nums.empty()) return 0;
int res = 0;
vector<bool> check(nums.size(), false);
for(int i = 0; i < nums.size(); ++i){
if(check[i]){
continue;
}
int tmp = 0;
int k = i;
while(!check[k]){
check[k] = true;
tmp++;
k = nums[k];
}
res = max(res, tmp);
}
return res;
}
};

//Set
class Solution {
public:
int arrayNesting(vector<int>& nums) {
if(nums.empty()) return 0;
int res = 0;
unordered_set<int> st;
for(int i = 0; i < nums.size(); ++i){
if(st.find(nums[i]) != st.end()){
continue;
}
int tmp = 0;
int k = i;
while(st.find(nums[k]) == st.end()){
st.insert(nums[k]);
tmp++;
k = nums[k];
}
res = max(res, tmp);
}
return res;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.