算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: