Golang, 32ms, 100%


  • 0
    D

    Golang, 2 solutions:

    32ms:

    func arrayNesting(nums []int) int {
        maxsize := 0
        
        for i := 0; i < len(nums); i ++ {
            size := 0
            for k := i; nums[k] >= 0; size++ {
                ak := nums[k]
                nums[k] = -1
                k = ak
            }
            maxsize = max(maxsize, size)
        }
        return maxsize
    }
    
    func max(a, b int) int {
        if a > b {
            return a
        }
        return b
    }
    

    39ms:

    func arrayNesting(nums []int) int {
        res := 0
        for i := 0; i < len(nums); i++ {
            if nums[i] < 0 {
                continue
            }
            length, val := 1, nums[i]
            for abs(val) != i {
                length++
                val = nums[abs(val)]
                nums[abs(val)] *= -1
            }
            res = max(res, length)
        }
        return res
    }
    
    func abs(s int) int {
        if s < 0 {
            s = -s
            return s
        }
        return s
    }
    
    func max(a, b int) int {
        if a > b {
            return a
        }
        return b
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.