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;    }};
原创粉丝点击