【leetcode每日刷题】128. Longest Consecutive Sequence

171 篇文章 0 订阅
94 篇文章 1 订阅

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

一、使用先排序,然后统计最长连续序列的方法。

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        nums = sorted(nums)
        max_len = 1
        cur_len = 1
        for i in range(1, len(nums)):
            if nums[i] != nums[i-1]:
                if nums[i] == nums[i-1] + 1:
                    cur_len += 1
                else:
                    max_len = max(max_len, cur_len)
                    cur_len = 1
        return max(max_len, cur_len)

二、使用hashmap,key,value的值分别为当前值与边界的范围。使用left和right的值更新当前的边界范围,更新当前值的时候也更新边界。

import java.util.HashMap;

// 100, 4, 200, 1, 3, 2
class num128 {
    public int longestConsecutive(int[] nums) {
        int max = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int num:nums){
            if(map.containsKey(num)) continue;
            int left = map.getOrDefault(num-1, 0);
            int right = map.getOrDefault(num+1, 0);
            int sum = left + right + 1;
            max = Math.max(sum, max);
            map.put(num, sum);
            if(left > 0) map.put(num-left, sum);
            if(right > 0) map.put(num+right, sum);
        }
        return max;
    }
    public static void main(String[] args) {
        num128 solution = new num128();
        int[] nums = {100, 4, 200, 1, 3, 2};
        int result = solution.longestConsecutive(nums);
        System.out.println(result);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值