import java.util.ArrayList;
import java.util.List;
/**
* @author xnl
* @Description:
* @date: 2022/7/3 23:05
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[] A = {5,4,0,3,1,6,2};
System.out.println(solution.arrayNesting3(A));
}
/**
* 暴力搜索
* 不行,超时
* @param nums
* @return
*/
public int arrayNesting(int[] nums) {
int ans = 0;
for (int i = 0; i < nums.length; i++){
ans = Math.max(calculation(nums, i), ans);
}
return ans;
}
private int calculation(int[] nums, int begin){
List<Integer> list = new ArrayList<>();
while (!list.contains(begin)){
list.add(begin);
begin = nums[begin];
}
return list.size();
}
/**
* 根据官方给的题解,可以发现,其实在一个有效的结果集中,无论是从什么位置开始,只要经过的路线,下一次肯定不会再走一次,
* 所以可以避免重复计算
*
* @param nums
* @return
*/
public int arrayNesting2(int[] nums) {
int res = 0;
boolean[] visited = new boolean[nums.length];
for (int i = 0; i < nums.length; i++){
if (!visited[i]){
// 记录一下环口,如果到了环口退出
int begin = nums[i], count = 1;
while (begin != i) {
begin = nums[begin];
count++;
visited[begin] = true;
}
res = Math.max(res, count);
}
}
return res;
}
/**
* 借鉴官方答案,修改数组
* 遍历过的数组,把他的结果改为-1
* @param nums
* @return
*/
public int arrayNesting3(int[] nums) {
int res = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] != -1){
int start = nums[i], count = 1;
while (start != -1){
// 提前存储结果
int temp = start;
start = nums[start];
count++;
nums[temp] = -1;
}
res = Math.max(res, count);
}
}
return res;
}
}
力扣:565. 数组嵌套
最新推荐文章于 2022-07-18 01:40:12 发布