leetcode 565. Array Nesting
来源:互联网 发布:九院吴巍 知乎 编辑:程序博客网 时间:2024/06/05 20:45
1.题目
A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0, N - 1].
给一个下标从0开始的长度为N的数组A,数组元素为[0,N-1]的所有数字。
集合S的定义如下:
Sets S[K] for 0 <= K < N are defined as follows:
S[K] = { A[K], A[A[K]], A[A[A[K]]], … }.
集合S是有限的,而且不包含重复元素。
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.
求从A的元素来构造的集合S的最大长度。
Example 1:
Input: A = [5,4,0,3,1,6,2]
Output: 4
Explanation:
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].
2.分析
以数组A = [5,4,0,3,1,6,2]为例。
从下标i=0开始遍历
i=0, S={A[0],A[5],A[6],A[2]}
i=1, S={A[1],A[4]}
i=2,S={A[0],A[5],A[6],A[2]}
i=3,S={A[3]}
i=4, S={A[1],A[4]}
i=5,S={A[0],A[5],A[6],A[2]}
i=6,S={A[0],A[5],A[6],A[2]}
可以看到,属于同一个集合的元素无论从哪一个开始,最终形成的集合都是一样的。
我们只需要遍历一次,把一个元素加入集合后将其标记为负数表示已经访问过,同时计算集合大小。
3.代码
class Solution {public: int arrayNesting(vector<int>& nums) { int longest = 1; for (int i = 0; i < nums.size(); i++) { int count = 0; int cur = i; while (nums[cur] >= 0) { ++count; int pre = cur; cur = nums[cur]; nums[pre] = -1; } longest = longest < count ? count : longest; } return longest; }};
- [leetcode]565. Array Nesting
- [LeetCode]565. Array Nesting
- LeetCode * 565. Array Nesting
- [LeetCode]565. Array Nesting
- leetcode 565. Array Nesting
- leetcode 565. Array Nesting
- [LeetCode] 565. Array Nesting
- [leetcode]565. Array Nesting
- [leetCode]565. Array Nesting
- LeetCode 565. Array Nesting
- LeetCode 565. Array Nesting
- leetcode 565. Array Nesting
- leetcode 565. Array Nesting
- leetcode-565. Array Nesting
- LeetCode:M-565. Array Nesting
- [Leetcode] 565. Array Nesting 解题报告
- leetcode array nesting
- leetcode(565). Array Nesting
- 【转载】ABAP MIGO 冲销 BAPI_GOODSMVT_CANCEL 源代码
- 一个Java的简单小程序(2)
- Springboot 整合 Dubbo/ZooKeeper 详解 SOA 案例
- 嵌入式中C语言volatile和const的作用
- 【剑指offer】面试题 7:重建二叉树
- leetcode 565. Array Nesting
- vue入门--环境搭建
- 网络---路由生产算法调研
- 【转载】REUSE_ALV_GRID_DISPLAY ALV表格数据 双击事件
- 类中的四个默认成员函数+运算符重载
- C语言关键字const
- Web 前端代码规范
- springBoot 集成 Quartz任务调度
- cartographer源码分析(8)-common-make_unique.h