码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode OJ】Longest Consecutive Sequence

时间:2014-05-05 22:55:22      阅读:552      评论:0      收藏:0      [点我收藏+]

标签:blog   class   code   tar   color   get   

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

 

【LeetCode OJ】Longest Consecutive Sequence,布布扣,bubuko.com

【LeetCode OJ】Longest Consecutive Sequence

标签:blog   class   code   tar   color   get   

原文地址:http://www.cnblogs.com/zzzdevil/p/3704762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!