【LeetCode】565. Array Nesting 解题报告(Python & C++)
作者: 负雪明烛
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:
- N is an integer within the range [1, 20,000].
- The elements of A are all distinct.
- 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++)的更多相关文章
- [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 ...
- 【LeetCode】154. Find Minimum in Rotated Sorted Array II 解题报告(Python)
[LeetCode]154. Find Minimum in Rotated Sorted Array II 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
- 【LeetCode】01 Matrix 解题报告
[LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...
- 【LeetCode】Largest Number 解题报告
[LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...
- 【LeetCode】Gas Station 解题报告
[LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...
随机推荐
- python—模拟生成双色球号
双色球规则:"双色球"每注投注号码由6个红色球号码和1个蓝色球号码组成.红色球号码从1--33中不重复选择:蓝色球号码从1--16中选择. # -*- coding:UTF-8 - ...
- 在windows下使用shell,运行shell脚本
在Windows操作系统下运行Shell脚本,缺少的只是一个Git软件.其下载路径为Git - Downloading Package. 安装之后,将安装路径下的bin文件夹的路径作为环境变量.于是我 ...
- mysql-日期时间函数大全
DAYOFWEEK(date) 返回日期date是星期几(1=星期天,2=星期一,--7=星期六,ODBC标准)mysql> select DAYOFWEEK('1998-02-03'); ...
- Flume(三)【进阶】
[toc] 一.Flume 数据传输流程 重要组件: 1)Channel选择器(ChannelSelector) ChannelSelector的作用就是选出Event将要被发往哪个Channel ...
- 零基础学习java------26--------获取省访问量的top3,APP版本数据分析,事务,json,json字符串与对象间的相互转换,求电影平均分
一. day23中的ip,url案例(前面答案错了) 思路分析: 1.创建javabean,用来存储ip.txt各字段的信息 2. 创建java工具类,封装相应的方法 (1) 加载读取ip.txt文档 ...
- Hibernate 总结(转)
JMX:Java Management Extensions.JCA: J2EE Contector ArchitectureJNDI: Java Namind and Directory Inter ...
- java中super的几种用法,与this的区别
1. 子类的构造函数如果要引用super的话,必须把super放在函数的首位. class Base { Base() { System.out.println("Base"); ...
- Private Destructor
Predict the output of following programs. 1 #include <iostream> 2 using namespace std; 3 4 cla ...
- yaml 配置文件的语法。
1.基本语法 1. k:(空格)v:表示一对键值对(注意:空格必须有): 2.以**空格**的缩进来控制层级关系:只要是左对齐的一列数据,都是同一个层级的 3.值的驼峰写法和用"-" ...
- 【Java 基础】Java Enum
概览 在本文中,我们将看到什么是 Java 枚举,它们解决了哪些问题以及如何在实践中使用 Java 枚举实现一些设计模式. enum关键字在 java5 中引入,表示一种特殊类型的类,其总是继承jav ...