[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 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}
解法 :
这个题实际上是找到最大的环。要注意的一点是,一旦在前一个不同的环中被访问过,它就不会出现在当前环中,可以忽略。
The idea is to, start from every number, find circles in those index-pointer-chains, every time you find a set (a circle) mark every number as visited (-1) so that next time you won't step on it again.
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Solution { public int arrayNesting( int [] a) { int maxsize = 0 ; for ( int i = 0 ; i < a.length; i++) { int size = 0 ; for ( int k = i; a[k] >= 0 ; size++) { int ak = a[k]; a[k] = - 1 ; // mark a[k] as visited; k = ak; } maxsize = Integer.max(maxsize, size); } return maxsize; } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution( object ): def arrayNesting( self , nums): """ :type nums: List[int] :rtype: int """ ans, step, n = 0 , 0 , len (nums) seen = [ False ] * n for i in range (n): while not seen[i]: seen[i] = True i, step = nums[i], step + 1 ans = max (ans, step) step = 0 return ans |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution { public : int arrayNesting(vector< int >& a) { size_t maxsize = 0; for ( int i = 0; i < a.size(); i++) { size_t size = 0; for ( int k = i; a[k] >= 0; size++) { int ak = a[k]; a[k] = -1; // mark a[k] as visited; k = ak; } maxsize = max(maxsize, size); } return maxsize; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架