565. Array Nesting

162 篇文章 0 订阅
53 篇文章 0 订阅

565. Array Nesting


Analysis

中午吃啥~—— [ummmm~]

A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], … } subjected to the rule below.
Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.
第一次做的时候很简单的想到两个循环(时间复杂度O(n*n)),最后发现大数据过不了,会TLE,然后看了一下大神们的做法,都只用了一个循环,也就是说之前已经遍历过得数据就不用再遍历一次了,因为这个每组数是一个循环,出现的点再考虑的话,无非是起点不一样,但是循环的数据数目还是一样的。如果出现的点再考虑的话,出现的结果和之前是一样的。

Implement

TLE solution

class Solution {
public:
    int arrayNesting(vector<int>& nums) {
        int len = nums.size();
        int res = INT_MIN;
        for(int i=0; i<len; i++){
            vector<int> visit(len, 0);
            int cnt = 0;
            int j = i;
            while(1){
                if(visit[nums[j]] == 1){
                    res = max(res, cnt);
                    break;
                }
                else{
                    cnt++;
                    visit[nums[j]] = 1;
                    j = nums[j];
                }

            }
        }
        return res;
    }
};

AC solution

class Solution {
public:
    int arrayNesting(vector<int>& nums) {
        int len = nums.size();
        int res = INT_MIN;
        vector<int> visit(len, 0);
        for(int i=0; i<len; i++){
            int cnt = 0;
            int j = i;
            while(1){
                if(visit[nums[j]] == 1){
                    res = max(res, cnt);
                    break;
                }
                else{
                    cnt++;
                    visit[nums[j]] = 1;
                    j = nums[j];
                }

            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值