当前位置:网站首页>0图中等 LeetCode565. 数组嵌套
0图中等 LeetCode565. 数组嵌套
2022-08-11 01:40:00 【18阿鲁】
描述
索引从0开始长度为N的数组A,包含0到N - 1的所有整数。找到最大的集合S并返回其大小,其中 S[i] = {A[i], A[A[i]], A[A[A[i]]], … }且遵守以下的规则。
假设选择索引为i的元素A[i]为S的第一个元素,S的下一个元素应该是A[A[i]],之后是A[A[A[i]]]… 以此类推,不断添加直到S出现重复的元素。
示例 1:
输入: A = [5,4,0,3,1,6,2]
输出: 4
解释:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
其中一种最长的 S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
提示:
1 <= nums.length <= 105
0 <= nums[i] < nums.length
A中不含有重复的元素。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/array-nesting
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析
从一个点出发,一定会再次回到这个点,即构成环;
数值不重复,说明环与环不相交;
寻找最大的环;
class Solution {
public int arrayNesting(int[] nums) {
int ans = 0;
boolean[] visited = new boolean[nums.length];
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (visited[i]) {
continue;
}
int size = 1;
visited[i] = true;
while (!visited[num]) {
size++;
visited[num] = true;
num = nums[num];
}
ans = Math.max(size,ans);
}
return ans;
}
}
边栏推荐
- Data Analysis Interview Manual "SQL"
- Section 4-6 of the first week of the second lesson: Appreciation of medical prognosis cases + homework analysis
- 数据的存储(下)——浮点型在内存中的存储
- 如何开展性能测试,你知道吗?
- This Thursday evening at 19:00, Lesson 5 of the sixth phase of knowledge empowerment丨OpenHarmony WiFi subsystem
- [The method of calling the child page from the parent page of the iframe] Stepping on the pit: It is the key to use `[x]` when getting elements. You cannot use `.eq(x)`, otherwise it will not be obtai
- 生信实验记录(part2)--tf.reduce_sum()用法介绍
- 连流量染色都没有,你说要搞微服务?
- C # - delegate detailed usage
- wincc如何实现远程监控1200PLC
猜你喜欢
随机推荐
88Q2110 access C45 phy address through C22
本周四晚19:00知识赋能第六期第5课丨OpenHarmony WiFi子系统
apache+PHP+MySQL+word press, page error when installing word press?
研发项目流程规范
url转成obj或者obj转成url的方法
21、阿里云oss
Alibaba 最新神作!耗时 182 天肝出来 1015 页分布式全栈手册太香了
生信实验记录(part2)--tf.reduce_sum()用法介绍
总结Qt中常用文件信息QFileInfo的获取:后缀,名称,路径,链接
【视频】报告分享|2021年保险行业数字化洞察
MySQL中的DDL常规操作总结
两日总结十一
SystemVerilog: 验证知识点点滴滴
MSTP——多生成树(案列+配置)
Exception: try catch finally throws throw
WinForm(五)控件和它的成员
络达开发---自定义BLE服务(二):功能实现
MySQL indexes and transactions
QT+VTK+PCL拟合圆柱并计算起始点、中止点
最新国产电源厂家及具体型号pin-to-pin替代手册发布