作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/search-a-2d-matrix/description/

题目描述

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: 6
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].

题目大意

给出了一个数组,找出从任意位置出发,把该位置的数字当做下一个索引的位置,最后肯定会终止于环路。找出最长的环长。

解题方法

本身思路很简单,就是用一个数组来保存某个位置是否被访问过,如果被访问过说明就是成了一个环,终止并记录最大环长。

直接这么做会超时,一个很机智的做法是,把visited数组放到for循环的外边,这样可以当新的环路计算的时候,如果以前的环访问过该位置的话,就不再计算了。道理是,给出的数组nums的数字范围是0~N-1,也就是说没有重复的数字,那么前面访问过的一个串的长度不会小于后面。

比如题目中给出的例子,在对以index = 0开始的串进行遍历的时候,会对0,5,6,2这几个位置进行标记过已经访问了。当index = 5,6,2时,以index开头的串的长度不会超过以0开头的串的长度。

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

代码:

class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 放在这里
visited = [False] * len(nums)
ans = 0
for i in xrange(len(nums)):
road = 0
while not visited[i]:
road += 1
# 下面两行的顺序不能变
visited[i] = True
i = nums[i]
ans = max(ans, road)
return ans

C++代码如下:

class Solution {
public:
int arrayNesting(vector<int>& nums) {
int res = 0;
const int N = nums.size();
vector<bool> visited(N, false);
for (int i = 0; i < N; i ++) {
int path = 0;
while (!visited[i]) {
visited[i] = true;
path += 1;
i = nums[i];
}
res = max(res, path);
}
return res;
}
};

日期

2018 年 3 月 6 日
2018 年 12 月 15 日 —— 今天四六级

【LeetCode】565. Array Nesting 解题报告(Python & C++)的更多相关文章

  1. [LeetCode] 565. Array Nesting 数组嵌套

    A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest ...

  2. 【LeetCode】154. Find Minimum in Rotated Sorted Array II 解题报告(Python)

    [LeetCode]154. Find Minimum in Rotated Sorted Array II 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...

  3. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  4. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  5. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  6. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  7. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  8. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  9. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

随机推荐

  1. php5.6升级7

    1. 检查当前安装的 PHP查看当前 PHP 版本 php -v查看当前 PHP 相关的安装包 yum list installed | grep php2. 更换 RPM 源#Centos 5.X: ...

  2. Selenium-IDE在火狐上的扩展

    昨天突然想学学 Selenium,就上网查了一些介绍,发现一些教程基本都是比较老版本的了,使用起来略有不便,所以今天试着写一些最新版本的.请参考Selenium官网.文章以下内容都是在 Mac 机器上 ...

  3. 进阶版的java面试

    来自一名2019届应届毕业生总结的Java研发面试题汇总(2019秋招篇)        2018年Java研发工程师面试题            Java研发工程师面试题(Java基础)       ...

  4. Rational Rose的安装及使用教程(包括菜单命令解释、操作向导说明、快捷命令说明)

    一.安装教程 我安装时用的是镜像文件,所以安装前需要辅助软件来处理镜像文件.我用到的是UltraISO.UltraISO中文名叫软碟通 是一款功能强大而又方便实用的光盘映像文件的制作/编辑/转换工具, ...

  5. 网卡命令ifconfig

    • ifconfig • service network restart • ifdown eth0 • ifdown eth0 #linux下run networkexport USER=lizhe ...

  6. JS模块化,Javascript 模块化管理的历史

    模块管理这个概念其实在前几年前端度过了刀耕火种年代之后就一直被提起. 直接回想起来的就是 cmd amd commonJS 这三大模块管理的印象.接下来,我们来详细聊聊. 一.什么是模块化开发 为了让 ...

  7. mysql explain using index condition

    Using where:表示优化器需要通过索引回表查询数据:Using index:表示直接访问索引就足够获取到所需要的数据,不需要通过索引回表:Using index condition:在5.6版 ...

  8. Linux学习 - 权限管理命令

    一.chmod(change the permissions mode of a file) 1 功能 改变文件或目录权限 root 与 所有者 可进行此操作 2 语法 chmod  [(ugoa) ...

  9. spring注解-bean生命周期

    https://www.jianshu.com/p/70b935f2b3fe bean的生命周期 bean创建---初始化----销毁的过程 容器管理bean的生命周期 对象创建:容器启动后调用bea ...

  10. 【面试】【Linux】【Web】基础概念

    1. HTTP https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol 2. TCP handshake https://en.wikipe ...