力扣:565. 数组嵌套


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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值