LintCode:最长连续序列

LintCode:最长连续序列

题目要求O(n)复杂度,我这个算法虽然通过了,但是排序操作至少就是O(nlgn)的复杂度了,额,还得再想想。

class Solution:
    """
    @param num, a list of integer
    @return an integer
    """
    def longestConsecutive(self, num):
        # write your code here
        if not num:
            return
        num = sorted(list(set(num)))
        ans = 1
        tmp = 1
        for i in range(1, len(num)):
            if num[i] - num[i-1] == 1 or num[i] - num[i-1] == 0:
                tmp += 1
            else:
                tmp = 1
            ans = max(ans, tmp)
        return ans

你可能感兴趣的:(lintcode,python)