道阻且长,行则将至,走慢|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-01 17:51阅读: 13评论: 0推荐: 0

[LeetCode Hot 100] LeetCode128. 最长连续序列

题目描述

思路


将数组所有点映射到一个数轴上,可以发现问题变为求每段区间首元素到尾元素的长度的最大值
区间的长度:区间尾元素值-区间首元素值 + 1

方法一:超出时间限制

这个方法是最初自己想到的,但是超时了,主要原因是程序会有冗余的遍历过程,增加了开销。
思路:(时间复杂度太高)

  1. 先把所有元素加入到哈希表中
  2. 遍历每一个元素n,看是否存在n+1,更新res
  3. 求最大res
class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums.length == 0) return 0;
		// 定义一个哈希表
        Set<Integer> set = new HashSet<>();
		// :将所有数添加到哈希表中
        for (int i : nums) set.add(i);
        int res = 0;
        
        for (int i = 0; i < nums.length; i ++) {
            int n = nums[i] + 1;
            while (set.contains(n)) {
                len = len + 1;
                n = n + 1;
            }
            res = Math.max(res, len);
        }
        return res;
    }
}

方法二:哈希表

求每段区间首元素到尾元素的长度的最大值

class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums.length == 0) return 0;
        Set<Integer> set = new HashSet<>();
        for (int i : nums) set.add(i);
        int res = 0;
        
        for (int num : nums) {
            if(!set.contains(num - 1)) {
				// 说明是区间的首元素
                int x = num;
                while(set.contains(x + 1)) {
                    x ++;
                }
                res = Math.max(res, x - num + 1);
            }
        }
        return res;
    }
}

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17870624.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(13)  评论(0编辑  收藏  举报
历史上的今天:
2022-12-01 Spring Boot中使用分页插件PageHelper
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.