565. Array Nesting

来源:互联网 发布:公路车骑行姿势 知乎 编辑:程序博客网 时间:2024/06/03 23:43

565. Array Nesting


Description:

A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0, N - 1].

Sets S[K] for 0 <= K < N are defined as follows:

S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }.

Sets S[K] are finite for each K and should NOT contain duplicates.

Write a function that given an array A consisting of N integers, return the size of the largest set S[K] for this array.

Example 1:

Input: A = [5,4,0,3,1,6,2]Output: 4Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
One of the longest S[K]:S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

Note:

  1. N is an integer within the range [1, 20,000].
  2. The elements of A are all distinct.
  3. Each element of array A is an integer within the range [0, N-1].

题意:遍历数组,找长度最大循环嵌套数组。
例如:
Input:A=[0,2,1]
Output:2
Explanation:A[1] = 2,A[2] =1;

解题思路:由于元素K是 0 <= K < N,每一组循环的元素的值都是固定不变的并且互不相同。只是开始循环的值不一样,但是这并不影响题目的结果(也就是循环嵌套数组的长度)。
例如:
Input: A = [5,4,0,3,1,6,2]
不讨论开始循环的值是否不同时,有那几组循环嵌套数组。
S[0]={A[0],A[5],A[6],A[2]} = {5,6,2,0}
S[4]={A[4],A[1]}={1,4}
S[3]={A[3]}={3}
其余S=1,2,5,6时,不过是上面几种情况,开始循环的值不一样而已,并不影响结果。


解题源码:
import java.util.Scanner;public class _565ArrayNesting {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int length = sc.nextInt();if(length<1||length>20000)return;int [] nums = new int[length];for(int i=0;i<length;i++){int temp = sc.nextInt();if(temp<0||temp>=length)return;nums[i] = temp;}int result = arrayNesting(nums);System.out.println(result);}public static int arrayNesting(int[] nums) {int length = nums.length;boolean [] visited = new boolean[length];int result = 0;for(int i=0;i<length;i++){int count = 0;int j = i;while(!visited[j]){visited[j]=true;j = nums[j];count ++;}result = Math.max(result, count);}return result;}      }


原创粉丝点击