题目链接:565. 数组嵌套
根据题意,考虑这样一张图,节点是 $0$ 到 $N - 1$ 的所有整数,而若对于任意 $i$,如果 $A_i = j$ 且 $i != j$,那么 $i$ 和 $j$ 之间有一条边。
这张图可以分为多个不相重叠的子图,其中最大的那张子图的节点集合就是题目所求的最大的集合 $S$。
import random
from typing import List
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
graphs, nodes = list(), set(nums)
while nodes:
k, subgraph = random.choice(tuple(nodes)), list()
while k in nodes:
nodes.remove(k)
subgraph.append(k)
k = nums[k]
graphs.append(subgraph)
return len(max(graphs, key=len))