​LeetCode刷题实战565:数组嵌套

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 数组嵌套,我们先来看题面:

https://leetcode-cn.com/problems/array-nesting/

You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].

You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:

The first element in s[k] starts with the selection of the element nums[k] of index = k.

The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.

We stop adding right before a duplicate element occurs in s[k].

Return the longest length of a set s[k].

索引从0开始长度为N的数组A,包含0到N - 1的所有整数。找到最大的集合S并返回其大小,其中 S[i] = {A[i], A[A[i]], A[A[A[i]]], ... }且遵守以下的规则。

假设选择索引为i的元素A[i]为S的第一个元素,S的下一个元素应该是A[A[i]],之后是A[A[A[i]]]... 以此类推,不断添加直到S出现重复的元素。

示例                         

输入: A = [5,4,0,3,1,6,2]
输出: 4
解释: 
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.

其中一种最长的 S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

解题

https://www.cnblogs.com/wangzaiguli/p/15133995.html

1:从题意可得,某些数字可以组成一个环,并且因为没有重复的数字,所以每个元素只能在一个环之中。求组成环最多的元素的个数。

2:创建一个长度为N的数组arr,来记录每个数字是否访问到了,没有访问到用初始值0 表示,访问倒了就用 1来标记。

3:每个数字都必定且仅在一个环中。所以遍历数组中的值,找到最大的环的长度即可。

class Solution {
    public int arrayNesting(int[] nums) {
  int length = nums.length;
        int[] arr = new int[length];
        int max = 0;
        int num;
        int value;
        for (int i = 0; i < length; i++) {
            if (arr[i] != 0) {
                continue;
            }
            arr[i] = 1;
            num = nums[i];
            int c = 1;
            while (arr[num] == 0) {
                value = nums[num];
                arr[num] = 1;
                num = value;
                c++;
            }
            max = Math.max(max, c);
        }
        return max;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-560题汇总,希望对你有点帮助!

LeetCode刷题实战561:数组拆分 I

LeetCode刷题实战562:矩阵中最长的连续1线段

LeetCode刷题实战563:二叉树的坡度

LeetCode刷题实战564:寻找最近的回文数

4bf001aa7aa67c07ba29539de8f52b49.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值