565. Array Nesting

来源:互联网 发布:淘宝企业店铺开店装修 编辑:程序博客网 时间:2024/06/06 19:50

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].

先写出了个O(N^2)的算法,心里虚虚的。。。果然不行。

int arrayNesting(vector<int>& nums) {    if (nums.size() <= 1)return nums.size();    int sum = 0;    for (int i = 0; i < nums.size(); i++){        vector<bool> flag(nums.size(), false);        int cnt = 0;        int pos = nums[i];        while (!flag[pos]){            cnt++;            flag[pos] = true;            pos = nums[pos];                }        sum = max(sum, cnt);    }    return sum;}

接着写成了个貌似O(N)的算法

int arrayNesting(vector<int>& nums) {    if (nums.size() <= 1)return nums.size();    int sum = 0;    vector<bool> flag(nums.size(), false);    for (int i = 0; i < nums.size();i++){        int cnt = 0;        //内部对于i的循环自我感觉很乱。。。        while (!flag[nums[i]]){            cnt++;            flag[nums[i]] = true;            i = nums[i];        }        sum = max(sum, cnt);    }    return sum;}

但是还是效率有些低,效率低的原因可能是因为内部的 i 的循环造成的。
所以,看了一下别人的参考版本。。。

int arrayNesting(vector<int>& nums) {    if (nums.size() <= 1)return nums.size();    int sum = 0;    vector<bool> flag(nums.size(), false);    for (int i = 0; i < nums.size(); i++){        int cnt = 0;        int k = i;        while (!flag[i]){            cnt++;            k = nums[k];            flag[k] = true;        }        sum = max(sum, cnt);    }    return sum;}