当前位置:网站首页>2022.07.18 _ a day
2022.07.18 _ a day
2022-07-31 07:40:00 【No. い】
565. 数组嵌套
题目描述
索引从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}
提示:
N
是[1, 20,000]
之间的整数.A
中不含有重复的元素.A
中的元素大小在[0, N-1]
之间.
- 深度优先搜索
- 数组
coding
1. 有向图
n 个不重复数字,范围【0,n - 1】,Can connect one by one or x A ring of directed graph i -> nums[i],Each ring does not exist cross,So once we pass a certain elements,In the future will not be using it again,So I can put it to,You can place to mark it as true.We need to traverse each ring,Get the most ring can be,如果是 isVis = true 的节点, It has been traversal,无需再次遍历,So just considering isVis = false 的节点开始遍历
class Solution {
public int arrayNesting(int[] nums) {
int res = 0;
boolean[] isVis = new boolean[nums.length];
for (int i = 0; i < nums.length; i++) {
int cnt = 0;
while (!isVis[i]) {
isVis[i] = true;
i = nums[i];
cnt ++;
}
res = Math.max(cnt, res);
}
return res;
}
}
2. In situ tag array
class Solution {
public int arrayNesting(int[] nums) {
int ans = 0, n = nums.length;
for (int i = 0; i < n; ++i) {
int cnt = 0;
while (nums[i] < n) {
int num = nums[i];
nums[i] = n;
i = num;
++cnt;
}
ans = Math.max(ans, cnt);
}
return ans;
}
}
3. 深搜 => 超时
class Solution {
public int arrayNesting(int[] nums) {
int max = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != -1) {
Stack<Integer> stack = new Stack();
max = Math.max(dfs(nums, i, stack), max);
}
}
return max;
}
private int dfs(int[] nums, int index, Stack<Integer> stack) {
if (nums[index] == -1) {
return 0;
}
if (stack.contains(nums[index])) {
return stack.size();
}
stack.push(nums[index]);
int size = dfs(nums, nums[index], stack);
nums[index] = -1;
stack.pop();
return size;
}
}
边栏推荐
- [PSQL] 复杂查询
- 基于LSTM的诗词生成
- Web浏览器工作流程解析
- How to use repeating-linear-gradient
- 2022.07.20_每日一题
- 批量翻译软件免费【2022最新版】
- Zero-Shot Learning & Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
- 第十六章:构建n(5,7)阶素数幻方
- 讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)
- opencv、pil和from torchvision.transforms的Resize, Compose, ToTensor, Normalize等差别
猜你喜欢
随机推荐
2022.07.13_每日一题
第9章 异常try...except...else...finally
Conditional statements of shell (test, if, case)
Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
Titanic 预测问题
【Go】Go 语言切片(Slice)
完美指南|如何使用 ODBC 进行无代理 Oracle 数据库监控?
基于LSTM的诗词生成
2022.07.20_每日一题
Bulk free text translation
tidyverse笔记——dplyr包
【网络攻防】常见的网络攻防技术——黑客攻防(通俗易懂版)
DAY18: Xss Range Clearance Manual
SQLite数据库连接字符串
2022.7.29 数组
小实战项目之——吃货联盟订餐系统
【解决】npm ERR A complete log of this run can be found in npm ERR
英语翻译软件-批量自动免费翻译软件支持三方接口翻译
HighTec 的安装与配置
codec2 BlockPool:不可读库