[LeetCode] 128. Longest Consecutive Sequence

题:https://leetcode.com/problems/longest-consecutive-sequence/description/

题目

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
#思路
两种方式
##1.
利用sort先对nums进行排序,然后遍历一次,如果当前遍历的和上次访问的数据相同则跳过,否则,若当前数据比上次访问的数据大一,则不同。

##2.
利用 set对nums进行set操作。

##Solution
https://leetcode.com/problems/longest-consecutive-sequence/solution/

#code
1.

class Solution:
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        nums.sort()
        
        longest_streak = 1
        current_streak = 1
        
        for i in range(1,len(nums)):
            if nums[i]!=nums[i-1]:
                if nums[i] == nums[i-1]+1:
                    current_streak +=1
                else:
                    longest_streak = max(longest_streak,current_streak)
                    current_streak =1
        return max(longest_streak,current_streak)
class Solution:
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        longest_streak = 0
        numsset = set(nums)
        
        for num in nums:
            if num-1 not in numsset:
                current_num = num
                current_streak = 1
                while current_num + 1 in numsset:
                    current_num +=1
                    current_streak +=1
                longest_streak = max(longest_streak,current_streak)
                
        return longest_streak

第二版

  1. 将 nums中元素放入 set中。
  2. 遍历set中元素,若 该元素+1的数 在set中,那么不断遍历递增元素,求出最长序列;若 元素-1的数 在 set中,那么就不求最长序列。因为当遍历到 该元素-1 的数时,统计最长序列会包含以该元素为起点的最长序列。
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int num:nums)
            set.add(num);
        int max = 0;
        for(int num : nums){
            if(set.contains(num -1))
                continue;
            int start =num;
            while(set.contains(num+1)){
                num++;
            }
            max = Math.max(max,num - start +1);
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值