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
2
3
4
5
6
7
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的所有元素,定义一个序列S,S的构成方式如下:S[i]={A[i], A[A[i]], A[A[A[i]]], ... },直到遇到重复元素,构造过程结束。我们需要找一个基于数组构造的、长度最长的序列S。

解决这题的思路很简单,我们只需要按照题目描述的那样,从不同的位置出发,分别构造序列S,比较每个序列的长度,返回最长的长度即可。

这个问题的关键在于记录当前位置是否被访问过,比较常用的做法是初始化一个访问数组,每访问一个元素,就将访问数组对应位置置为True,但这种方式会导致超时,我们有两种方法解决超时问题:

  1. 将访问数组放到循环外,这样,当从新的位置出发时,遇到了已访问过的元素,就可以直接跳过,因为给出的数组不存在重复元素,从前一个位置出发得到的序列长度必然大于从后面出发得到的序列。
  2. 由于给定数组中全是大于0的元素,我们可以将已访问过的元素置为-1,这样也能够起到记录是否访问过的作用,不需要另外的访问数组,还减小了空间复杂度。

代码:

方法1:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def arrayNesting(nums):
res = -1
count = 0
seen = [False] * len(nums)
for i in range(len(nums)):
while not seen[i]:
seen[i] = True
i = nums[i]
count += 1
res = max(res, count)
count = 0
return res

方法2:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
res = -1
count = 0
for i in range(len(nums)):
while nums[i] >= 0:
tmp_i, nums[i] = nums[i], -1
i = tmp_i
count += 1
res = max(res, count)
count = 0
return res