力扣:565. 数组嵌套

这篇博客介绍了两种方法实现数组环形遍历,第一种使用额外的访问标记数组,第二种则优化为原地标记,直接修改数组元素以避免额外空间。两种方法的时间复杂度均为O(n),空间复杂度分别为O(n)和O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用一个标记是否已经走过的数组,来统计是否已经走过 

class Solution {
    public int arrayNesting(int[] nums) {
        int n = nums.length;
        // 记录是否访问下标
        boolean[] vis = new boolean[n];
        int res = 0;
        for (int i = 0; i < n; i++){
            int count = 0;
            int cur = i;
            // 遍历这个环,统计这个环的大小
            while (!vis[cur]){
                vis[cur] = true;
                count++;
                cur = nums[cur];
            }
            res = Math.max(res, count);
        }
        return res;
    }
}

优化:不使用数组,使用原地标记

class Solution {
    // 原地标记没因为nums里面的数据是在nums.length里面的,那么也就是说,走过的点,我们可以把他修改掉
    public int arrayNesting(int[] nums) {
        int res = 0, n = nums.length;
        for (int i = 0; i < n; i++){
            int count = 0;
            int cur = i;
            while (nums[cur] < n){
                count++;
                int temp = nums[cur];
                // 修改值,让这个值变成已经走过了
                nums[cur] = n;
                cur = temp;
            }
            res = Math.max(res, count);
        }
        return res;
    }
}

时间复杂度:o(n) 空间复杂度: o(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值