当前位置:网站首页>2022.07.18_每日一题
2022.07.18_每日一题
2022-07-31 06:07:00 【诺.い】
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】,可以连成一张由一个或 x 个环组成的有向图 i -> nums[i],每个环不存在交叉,所以我们一旦经过某个元素,以后就不可能再用上它,所以可以把它抹去,可以原地地将它标记为 true。我们只需遍历每个环,获取最大环即可,如果是 isVis = true 的节点, 则它已经遍历过,无需再次遍历,故只需考虑从 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. 原地标记数组
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;
}
}
边栏推荐
- opencv、pil和from torchvision.transforms的Resize, Compose, ToTensor, Normalize等差别
- 【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
- gstreamer's caps event and new_segment event
- 04-SDRAM: Read Operation (Burst)
- 电压源的电路分析知识分享
- shell之条件语句(test、if、case)
- Install and use uView
- tidyverse笔记——管道函数
- 新瓶陈酒 --- 矩阵快速幂
- Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software
猜你喜欢
随机推荐
shell之条件语句(test、if、case)
Zotero | Zotero translator插件更新 | 解决百度学术文献无法获取问题
嵌入式系统驱动初级【2】——内核模块下_参数和依赖
tidyverse笔记——管道函数
Explain the example + detail the difference between @Resource and @Autowired annotations (the most complete in the entire network)
04-SDRAM:读操作(突发)
R——避免使用 col=0
codec2 BlockPool:unreadable libraries
科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】
零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
英语翻译软件-批量自动免费翻译软件支持三方接口翻译
什么是半波整流器?半波整流器的使用方法
【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止
安装gstreamer开发依赖库到项目sysroot目录
2.(1)栈的链式存储、链栈的操作(图解、注释、代码)
项目 - 如何根据最近30天、最近14天、最近7天、最近24小时、自定义时间范围查询MySQL中的数据?
How to use repeating-linear-gradient
知识、创新、回报。
深度学习通信领域相关经典论文、数据集整理分享









