Daily LeetCode 565. Array Nesting
https://leetcode.com/problems/array-nesting/
Medium
问题描述
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:
1 | Input: A = [5,4,0,3,1,6,2] |
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].
题目分析:
给定一个长度为N的数组,数组包含从0~N-1
的所有元素,定义一个序列S,S的构成方式如下:S[i]={A[i], A[A[i]], A[A[A[i]]], ... }
,直到遇到重复元素,构造过程结束。我们需要找一个基于数组构造的、长度最长的序列S。
解决这题的思路很简单,我们只需要按照题目描述的那样,从不同的位置出发,分别构造序列S,比较每个序列的长度,返回最长的长度即可。
这个问题的关键在于记录当前位置是否被访问过,比较常用的做法是初始化一个访问数组,每访问一个元素,就将访问数组对应位置置为True,但这种方式会导致超时,我们有两种方法解决超时问题:
- 将访问数组放到循环外,这样,当从新的位置出发时,遇到了已访问过的元素,就可以直接跳过,因为给出的数组不存在重复元素,从前一个位置出发得到的序列长度必然大于从后面出发得到的序列。
- 由于给定数组中全是大于0的元素,我们可以将已访问过的元素置为-1,这样也能够起到记录是否访问过的作用,不需要另外的访问数组,还减小了空间复杂度。
代码:
方法1:
1 | class Solution: |
方法2:
1 | class Solution: |