LeetCode--Longest Consecutive Sequence(最长连续序列)Python

题目:

给定一个乱序的整数数组,找到最长连续元素序列的长度。比如给定数组[100, 4, 200, 1, 3, 2],其中最长的连续数组为[1,2,3,4],所以返回的最大长度为4。

解题思路:

因为考虑要降低复杂度,所以先将数据遍历一遍,存储到字典中。再从字典中不断拿出当前的整数相邻两个整数是否在字典中,若存在,则弹出这两个数,并将count+2,若当前整数相邻的两个数都不在字典中,则判断当前的count是否大于之前count的最大值,若大于,则更新最大值为当前的count。

代码(Python):

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        Dict = {}
        for i in nums:
            Dict[i] = 1   
        List = Dict.keys()       
        count_max = 0   
        while(len(Dict)):
            List = Dict.keys()
            count = 1
            temp_left = List[0]
            temp_right = List[0]
            Dict.pop(temp_left)
            while(1):
                if temp_left-1 in Dict and temp_right+1 in Dict:
                    count = count+2
                    temp_left = temp_left-1
                    temp_right = temp_right+1
                    Dict.pop(temp_left)
                    Dict.pop(temp_right)
                    continue
                elif temp_left-1 not in Dict and temp_right+1 in Dict:
                    count = count+1
                    temp_right = temp_right+1
                    Dict.pop(temp_right)
                    continue
                elif temp_left-1 in Dict and temp_right+1 not in Dict:
                    count = count+1
                    temp_left = temp_left-1
                    Dict.pop(temp_left)
                    continue
                else:
                    if count>count_max:
                        count_max=count
                        break
                    else:
                        break
        return count_max

你可能感兴趣的:(LeetCode)