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:
- N is an integer within the range [1, 20,000].
- The elements of A are all distinct.
- 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;} }
阅读全文
0 0
- [leetcode]565. Array Nesting
- [LeetCode]565. Array Nesting
- 565. Array Nesting
- LeetCode * 565. Array Nesting
- [LeetCode]565. Array Nesting
- 565. Array Nesting
- 565. Array Nesting
- leetcode 565. Array Nesting
- leetcode 565. Array Nesting
- 565. Array Nesting
- [LeetCode] 565. Array Nesting
- [leetcode]565. Array Nesting
- [leetCode]565. Array Nesting
- LeetCode 565. Array Nesting
- 565. Array Nesting
- LeetCode 565. Array Nesting
- 565. Array Nesting
- 565. Array Nesting
- guava Optional api使用
- android.support.v7.app.AlertDialog显示异常
- android布局--Android fill_parent、wrap_content和match_parent的区别
- log4j.properties配置详解与实例
- Extjs6 treepanel store无法加载请求后台URL数据bug
- 565. Array Nesting
- Java基础(七)---- 反射与框架的问题
- 技术宅男既要提升编程技术也要加强沟通能力
- 一个在网上找到的用C++写的游戏
- 前端网页
- 有道云6.0 remove Ad
- 使用IntelliJ IDEA 配置Maven(入门)
- 在idea中用git导入的maven项目,启动Tomcat报错,求大神!
- 关于应用的Splash启动页