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.
方法一:暴力求解产生超时:
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
resmax = 0
for i in range(len(nums)):
index = nums[i]
count = 1
myset =set()
myset.add(index)
while(nums[index] not in myset):
index = nums[index]
myset.add(index)
count +=1
# print(index)
if count>resmax:
resmax = count
#print(myset,count)
return resmax
方法二:参考解法很巧妙,主要是使用标记的技巧
把nums[]里面遍历过的数字index标记,下次再遇到这个index的时候就continue,因为标记过的数字说明这个长度已经是前面的一个子集了。所以他的复杂度是O(n)
public int arrayNesting(int[] nums) {
int res = 0;
for (int i=0;i<nums.length;i++) {
if (nums[i] < 0) continue;
int length = 1, val = nums[i];
while (Math.abs(val) != i) {
length++;
val = nums[Math.abs(val)];
nums[Math.abs(val)] *= -1;
}
res = Math.max(res, length);
}
return res;
}