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: 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:
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[i] = {A[i], A[A[i]], A[A[A[i]]], … },元素添加到集合S中的停止条件是当插入重复元素时;根据定义,返回找到满足条件的集合S的最长长度;
解法一(超时):很容易想到的一个方法就是利用暴力求解,从数组的下标0开始一直到下标n-1,对比每一次产生的集合,返回最长的那个;但是,这种算法的时间复杂度为O(n2);
class Solution {
public int arrayNesting(int[] nums) {
int maxLen = 1;
for (int i = 0; i < nums.length; i++) {
int preNum = i;
Set<Integer> table = new HashSet<>();
while(!table.contains(nums[preNum])) {
table.add(nums[preNum]);
preNum = nums[preNum];
}
maxLen = Math.max(maxLen, table.size());
}
return maxLen;
}
}
解法二:观察下面的图我们可以知道,每次一个取得的一个集合S,里面所有元素构成了一个回路,这时,不管我们访问这里面的哪个元素,最终得到的集合S都是相同的,因此,我们可以通过标记这些元素,就不必做重复的运算,最终算法的时间复杂度为O(n);
class Solution {
public int arrayNesting(int[] nums) {
int maxLen = 1;
boolean[] visited = new boolean[nums.length];
for (int i = 0; i < nums.length; i++) {
if (!visited[i]) {
int preNum = i;
Set<Integer> table = new HashSet<>();
while(!table.contains(nums[preNum])) {
table.add(nums[preNum]);
preNum = nums[preNum];
visited[preNum] = true;
}
maxLen = Math.max(maxLen, table.size());
}
}
return maxLen;
}
}