leetcode 565. Array Nesting

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.
方法一:暴力求解产生超时:

class Solution:
    def arrayNesting(self, nums: List[int]) -> int:
        resmax = 0
        for i in range(len(nums)):
            index = nums[i]
            count = 1
            myset =set()
            myset.add(index)
            while(nums[index] not in myset):
                index = nums[index]
                myset.add(index)
                count +=1
                # print(index)
            
            if count>resmax:
                resmax = count
            #print(myset,count)
        return resmax

方法二:参考解法很巧妙,主要是使用标记的技巧
把nums[]里面遍历过的数字index标记,下次再遇到这个index的时候就continue,因为标记过的数字说明这个长度已经是前面的一个子集了。所以他的复杂度是O(n)

public int arrayNesting(int[] nums) {
    int res = 0;
    for (int i=0;i<nums.length;i++) {
        if (nums[i] < 0) continue;
        int length = 1, val = nums[i];
        while (Math.abs(val) != i) {
            length++;
            val = nums[Math.abs(val)];
            nums[Math.abs(val)] *= -1;
        }
        res = Math.max(res, length);
    }
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值