leetcode 565. Array Nesting

本是古典 何须时尚 2022-06-13 03:06 218阅读 0赞

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.代码

  1. class Solution {
  2. public:
  3. int arrayNesting(vector<int>& nums) {
  4. int longest = 1;
  5. for (int i = 0; i < nums.size(); i++) {
  6. int count = 0;
  7. int cur = i;
  8. while (nums[cur] >= 0) {
  9. ++count;
  10. int pre = cur;
  11. cur = nums[cur];
  12. nums[pre] = -1;
  13. }
  14. longest = longest < count ? count : longest;
  15. }
  16. return longest;
  17. }
  18. };

发表评论

表情:
评论列表 (有 0 条评论,218人围观)

还没有评论,来说两句吧...

相关阅读