首页 > 代码库 > 【LeetCode OJ】Longest Consecutive Sequence

【LeetCode OJ】Longest Consecutive Sequence

Problem Link:

http://oj.leetcode.com/problems/longest-consecutive-sequence/

This problem is a classical problem where we can reduce the running time by the help of hash table.

By given a list of numbers, we can find the longest consecutive sequence by the following steps:

  1. Let H be a empty hash set, add all given numbers into H (duplicates will be removed)
  2. Let max_len = 0 denote the length of current longest consecutive sequence
  3. While H is not empty:
    1. count all n‘s smaller consecutive numbers in H and remove them from H
    2. count all n‘s larger consecutive numbers in H and remove them from H
    3. update max_len with the length of this consecutive sequence containing n

The python code is as follows.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution:
    # @param num, a list of integer
    # @return an integer
    def longestConsecutive(self, num):
        """
        Find the longest consecutive number sequence by using hash map
        1) Add all numbers in the list to a hash set HS
        2) Let max_length = 0, which records the length of the current longest consecutive sequence
        3) For each number n in the hash set
                count the number of all n‘s left consecutive numbers in the hash set
                count the number of all n‘s right consecutive numbers in the hash set
                remove the counted numbers from the hash set
          Update the max_length with the length of this consecutive sequence contaning n.
        """
        # Conver the list to a hash set, this will remove the duplicates
        numbers = set(num)
        # Current max_len
        max_len = 0
         
        while numbers:
            # Get a number from the hash set
            x = numbers.pop()
            # This sequence only containing x is length of 1
            x_len = 1
            # Find all left consecutive numbers of x
            left = x-1
            while left in numbers:
                numbers.remove(left)
                left -= 1
            # Find all right consecutive numbers of x
            right = x+1
            while right in numbers:
                numbers.remove(right)
                right += 1
            # Update the max_len
            max_len = max(max_len, right-left-1)
         
        return max_len