題目地址:
https://www.lintcode.com/problem/array-nesting/description
給定一個長度爲的數組,內容是(順序可能是亂的)。現在令,求。
思路是枚舉每一個,同時用一個哈希表記錄裏的數字以便於查重,然後分別計算。代碼如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
/**
* @param nums: an array
* @return: the longest length of set S
*/
public int arrayNesting(int[] nums) {
// Write your code here
int res = 1;
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
// 如果已經含有當前數了,說明之前算過,那就不用算了
if (set.contains(nums[i])) {
continue;
}
int cur = nums[i], len = 0;
while (!set.contains(cur)) {
set.add(cur);
cur = nums[cur];
// 累加長度
len++;
}
res = Math.max(res, len);
}
return res;
}
}
時空複雜度。