当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
Chapter 17: go back to find the entrance to the specified traverse, "ma bu" or horse stance just look greedy, no back to search traversal, "ma bu" or horse stance just look recursive search NXM board
Third-party library-store
【微服务】 微服务学习笔记二:Eureka注册中心的介绍及搭建
【微服务】Nacos集群搭建以及加载文件配置
tidyverse笔记——管道函数
基于LSTM的诗词生成
在 ASP.NET Core 应用程序启动时运行代码的 3 种方法
Gradle剔除依赖演示
Kubernetes调度
解决win11/win10在登陆界面(解锁界面)点击获取每日壁纸无效的问题 - get Daily Lockscreen and Wallpaper - Win11/10的登录界面背景图片在哪里?
数据库概论 - MySQL的简单介绍
Difficulty comparison between high concurrency and multithreading (easy to confuse)
自动翻译软件-批量批量自动翻译软件推荐
科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
Database Principles Homework 2 — JMU
服务器和客户端信息的获取
从入门到一位合格的爬虫师,这几点很重要
HuffmanTree
Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)