Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

128. Longest Consecutive Sequence

Topics: Array Hash Table Union Find

Solution

Reference: https://hackmd.io/@CLKO/rkRVS_o-4?type=view

Implementation

class Solution {
    val boss = mutableMapOf<Int, Int>()

    fun findBoss(x: Int): Int {
        if (x == boss[x]) return x
        val currentBoss = findBoss(boss[x]!!)
        boss[x] = currentBoss
        return currentBoss
    }

    fun join(x: Int, y: Int) {
        val xBoss = findBoss(x)
        val yBoss = findBoss(y)
        boss[xBoss] = yBoss
    }

    fun longestConsecutive(nums: IntArray): Int {
        for (num in nums) {
            if (boss.containsKey(num)) continue
            boss[num] = num
            if (boss.containsKey(num - 1)) join(num - 1, num)
            if (boss.containsKey(num + 1)) join(num + 1, num)
        }

        val count = mutableMapOf<Int, Int>()

        for (num in boss.keys) {
            val currentBoss = findBoss(num)
            count[currentBoss] = count[currentBoss]?.let { it + 1 } ?: 1 
        }

        var ans = 0
        count.values.forEach { ans = max(ans, it) }

        return ans
    }
}