当前位置:网站首页>LeetCode 565. Array nesting
LeetCode 565. Array nesting
2022-07-19 16:57:00 【Sasakihaise_】
【DFS】 Because there are no repeating elements , Therefore, there will be no case that one vertex connects multiple vertices , So set up a visit Array , For each vertex dfs, If this vertex has been visited , It shows that he forms a ring . On the next vertex dfs Judge whether you have visited , If you have visited , It means that it is already in the ring .
In fact, it will be better understood if it is changed here
0 -> 5
1 -> 4
2 -> 0
3 -> 3
4 -> 1
5 -> 6
6 -> 2
In fact, it is an undirected graph , Just looking for the ring
class Solution {
// dfs
public int arrayNesting(int[] nums) {
int[] visit = new int[nums.length];
int max = 0;
for (var i = 0; i < nums.length; i++) {
if (visit[i] == 1) continue;
int idx = i, t = 0;
while(true) {
if (visit[idx] == 1) {
max = Math.max(max, t);
break;
}
t++;
visit[idx] = 1;
idx = nums[idx];
}
}
return max;
}
}
【 Union checking set 】 You can also find rings by using the union search set , Put on the same ring union get up , Then judge each union Just the size of
class Solution {
int[] f = new int[100001];
public int ask(int x) {
if (x == f[x]) return x;
return f[x] = ask(f[x]);
}
public void union(int x, int y) {
f[ask(x)] = ask(y);
}
public int arrayNesting(int[] nums) {
int n = nums.length;
for (var i = 1; i <= n; i++) f[i] = i;
for (var i = 0; i < n; i++) union(nums[i], i);
int[] cnt = new int[n + 1];
int ans = 0;
for (var i = 0; i < n; i++) {
ans = Math.max(ans, ++cnt[ask(i)]);
}
return ans;
}
}
边栏推荐
- Mecol studio djangoweb application framework +mysql database fourth training
- 【C语言】文件操作详解
- 3dmax导出fbx模型到unity
- [QNX hypervisor 2.2 user manual]8.3 guest triggered exit
- R3LIVE:一個實時魯棒、帶有RGB顏色信息的激光雷達-慣性-視覺緊耦合系統
- 字符集7-10
- JS operation date object
- Nacos cluster construction
- R3live: a real-time robust lidar inertial vision tight coupling system with RGB color information
- 302 周赛3 6121. 裁剪数字后查询第 K 小的数字 排序 6122. 使数组可以被整除的最少删除次数 数学
猜你喜欢
随机推荐
JS 之 操作 Function 函数
Jlink命令
arduino ‘ does not name a type报错
此异常最初是在此调用堆栈中引发的: FontFamily.GetName(int)
Using dynamic proxy to generate requestcode conveniently and safely
JVM 内存布局详解
codeforces每日5题(均1500)-第十八天
π-LSAM: 基于平面的激光雷达平滑和建图
Distributed notes (03) - redis of distributed cache (overview of stand-alone mode and redis cluster mode)
51world 如何修改渲染视频/窗口的大小 ?
STM32 interrupt plum blossom two degrees (one)
7.17 simulation summary
The computer cannot connect to the network after turning on the hotspot
302 周赛3 6121. 裁剪数字后查询第 K 小的数字 排序 6122. 使数组可以被整除的最少删除次数 数学
WCF -- realize the service with authentication and common error reporting
R3live: a real-time robust lidar inertial vision tight coupling system with RGB color information
第3章业务功能开发(添加市场活动备注)
TCP 通信流程
JS operation array
1805. Number of different integers in the string ●