-
Notifications
You must be signed in to change notification settings - Fork 0
565_ArrayNesting
a920604a edited this page Apr 14, 2023
·
1 revision
detect cycle
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), ret = 0;
vector<bool> visited(n, false);
for(int i=0;i<n;++i){
int size = 0, j = i;
while( visited[j] == false){
visited[j] = true;
j = nums[j];
size++;
}
ret = max(ret, size);
}
return ret;
}
};
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), ret = 0;
for(int i=0;i<n;++i){
int size = 0, j = i;
while( nums[j] >= 0){
int idx = nums[j];
nums[j] = -1;
j = idx;
size++;
}
ret = max(ret, size);
}
return ret;
}
};
- time complexity
O(n)
- space complexity
O(1)
footer