Swift O(n) implementation with 67 / 67 test cases passed. Runtime 52 ms


  • 1
    I
    class Solution {
        func longestConsecutive(nums: [Int]) -> Int {
            var ans = 0
            var set = Set<Int>()
            for var i = 0; i < nums.count; i++
            {
                set.insert(nums[i])
            }
            for var i = 0; i < nums.count; i++
            {
                if(!set.contains(nums[i] - 1))
                {
                    var j = nums[i]
                    while (set.contains(j))
                    {
                        j++
                    }
                    if(ans < (j - nums[i]))
                    {
                        ans = j - nums[i]
                    }
                }
            }
            return ans
        }
    }
    
    

Log in to reply
 

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