A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.

Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.

Example 1:

Input: A = [5,4,0,3,1,6,2]
Output: 4
Explanation:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

Note:

  1. N is an integer within the range [1, 20,000].
  2. The elements of A are all distinct.
  3. Each element of A is an integer within the range [0, N-1].

这道题让我们找嵌套数组的最大个数,给的数组总共有n个数字,范围均在 [0, n-1] 之间,题目中也把嵌套数组的生成解释的很清楚了,其实就是值变成坐标,得到的数值再变坐标。那么实际上当循环出现的时候,嵌套数组的长度也不能再增加了,而出现的这个相同的数一定是嵌套数组的首元素,博主刚开始没有想清楚这一点,以为出现重复数字的地方可能是嵌套数组中间的某个位置,于是用个 set 将生成的嵌套数组存入,然后每次查找新生成的数组是否已经存在。而且还以原数组中每个数字当作嵌套数组的起始数字都算一遍,结果当然是 TLE 了。其实对于遍历过的数字,我们不用再将其当作开头来计算了,而是只对于未遍历过的数字当作嵌套数组的开头数字,不过在进行嵌套运算的时候,并不考虑中间的数字是否已经访问过,而是只要找到和起始位置相同的数字位置,然后更新结果 res,参见代码如下:

解法一:

class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), res = INT_MIN;
vector<bool> visited(n, false);
for (int i = ; i < nums.size(); ++i) {
if (visited[nums[i]]) continue;
res = max(res, helper(nums, i, visited));
}
return res;
}
int helper(vector<int>& nums, int start, vector<bool>& visited) {
int i = start, cnt = ;
while (cnt == || i != start) {
visited[i] = true;
i = nums[i];
++cnt;
}
return cnt;
}
};

下面这种方法写法上更简洁一些,思路完全一样,参见代码如下:

解法二:

class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), res = INT_MIN;
vector<bool> visited(n, false);
for (int i = ; i < n; ++i) {
if (visited[nums[i]]) continue;
int cnt = , j = i;
while(cnt == || j != i) {
visited[j] = true;
j = nums[j];
++cnt;
}
res = max(res, cnt);
}
return res;
}
};

下面这种解法是网友 @edyyy 提醒博主的,可以优化解法二的空间,我们并不需要专门的数组来记录数组是否被遍历过,而是在遍历的过程中,将其交换到其应该出现的位置上,因为如果某个数出现在正确的位置上,那么它一定无法组成嵌套数组,这样就相当于我们标记了其已经访问过了,思路确实很赞啊,参见代码如下:

解法三:

class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), res = ;
for (int i = ; i < n; ++i) {
int cnt = ;
while (nums[i] != i) {
swap(nums[i], nums[nums[i]]);
++cnt;
}
res = max(res, cnt);
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/565

类似题目:

Nested List Weight Sum II

Flatten Nested List Iterator

Nested List Weight Sum

参考资料:

https://leetcode.com/problems/array-nesting/

https://leetcode.com/problems/array-nesting/discuss/102432/C%2B%2B-Java-Clean-Code-O(N)

https://leetcode.com/problems/array-nesting/discuss/232283/C%2B%2B-straightforward-solution-beats-100

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 565. Array Nesting 数组嵌套的更多相关文章

  1. [LeetCode] Array Nesting 数组嵌套

    A zero-indexed array A consisting of N different integers is given. The array contains all integers ...

  2. 【leetcode】565. Array Nesting

    You are given an integer array nums of length n where nums is a permutation of the numbers in the ra ...

  3. 【LeetCode】565. Array Nesting 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  4. [LeetCode] Patching Array 补丁数组

    Given a sorted positive integer array nums and an integer n, add/patch elements to the array such th ...

  5. [LeetCode] Rotate Array 旋转数组

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  6. [LeetCode] Contiguous Array 邻近数组

    Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. ...

  7. LeetCode Rotate Array 翻转数组

    题意:给定一个数组,将该数组的后k位移动到前n-k位之前.(本题在编程珠玑中第二章有讲) 思路: 方法一:将后K位用vector容器装起来,再移动前n-k位到后面,再将容器内k位插到前面. class ...

  8. 565. Array Nesting

    Problem statement: A zero-indexed array A consisting of N different integers is given. The array con ...

  9. Java实现 LeetCode 565 数组嵌套(没有重复值的数组)

    565. 数组嵌套 索引从0开始长度为N的数组A,包含0到N - 1的所有整数.找到并返回最大的集合S,S[i] = {A[i], A[A[i]], A[A[A[i]]], - }且遵守以下的规则. ...

随机推荐

  1. JVM的监控工具之jhat

    在上一篇文件文章中讲到了jhap的用法:https://www.cnblogs.com/cheng21553516/p/11223615.html,既然jhap可以转储堆的快照文件, 那么用什么来分析 ...

  2. 专栏《Elasticsearch 7.x从入门到精通》的相关源代码

    新版Elasticsearch 7.3 和 Spring Boot 2.1.7 集成演示项目       第一个项目:演示Elasticsearch 6.4.3 和Spring Boot 2.1.7集 ...

  3. C#使用splitContainer控件制作收缩展开面板

    C#使用splitContainer控件制作收缩展开面板 原创 2011年07月19日 17:18:02 标签: c# / object / 扩展 / 测试 15690         最近对Squi ...

  4. ABP中文网的一些BUG

    之前一些翻译了的文档没有及时更新.比如 IAsyncCrudAppService接口在很久之前的版本就已经改为了ICrudAppService,如果是在官网下载的最新实例中IAsyncCrudAppS ...

  5. windows下编写dll

    dll的优点 简单的说,dll有以下几个优点: 1) 节省内存.同一个软件模块,若是以源代码的形式重用,则会被编译到不同的可执行程序中,同时运行这些exe时这些模块的二进制码会被重复加载到内存中.如果 ...

  6. centos通过yum快速安装JDK1.8

    centos通过yum快速安装JDK1.8检索1.8的列表:yum list java-1.8*安装1.8.0的所有文件:yum install java-1.8.0-openjdk* -y 出现 C ...

  7. 【原创】Airflow 简介&如何部署一个健壮的 apache-airflow 调度系统

    声明 本文摘录了很多前辈的文章,原文如下: https://www.jianshu.com/p/2ecef979c606 Airflow 简介 Airflow是一个可编程,调度和监控的工作流平台,基于 ...

  8. python 自带模块 os模块

    os模块 首先可以打开cmd输入python进入交互界面  然后输入 dir(os) 就可以看到os的全部用法了  我们简单的举几个例子就行了. 写入os.getcwd()  可以查看当前所在路径 i ...

  9. nginx反向代理和负载均衡的基本配置

    一.反向代理的基本配置 在原本默认的nginx上修改server配置 server { listen 2222;#监听请求端口 server_name 192.168.100.3;#监听请求地址,ng ...

  10. odoo10学习笔记十七:controller

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/11189391.html 一:controller简述 odoo里面的controller相似于springM ...