1. 原题
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.
Example 1:
Input: A = [5,4,0,3,1,6,2]
Output: 4
Explanation:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
2.分析
- 采用循环读取的办法, 当出现环的时候停止
- 由于一个环无论从哪里开始,都最终会得到一样的数量的成员数量,所以我们将遍历过的环的成员的值设置成相反数,这样在进入遍历前判断如果这个数是负数就不再遍历他所在的环了
- 使用一个数据来记录最大值并且更新。
- 处理空集这种特殊情况
- 使用set来检测不会出现重复
3.代码
class Solution {
public:
int arrayNesting(vector<int>& nums) {
if(nums.empty()) return 0;
int ret_size = 0;
for(int i=0; i<nums.size(); i++){
if(nums[i] < 0) continue;
int cur = nums[i];
nums[i] = -nums[i];
set<int> st;
while(!st.count(cur) && cur >= 0){
st.insert(cur);
int temp = nums[cur];
nums[cur] = -nums[cur];
cur = temp;
}
if(st.size() > ret_size) ret_size = st.size();
}
return ret_size;
}
};