LeetCode【128】最长连续序列

题目:

分析:

1、最长连续序列的长度为 y-x+1,如1-4:4-1+1 = 4

2、不要被这里的On误导,不敢使用双层循环

3、只要找到最小的数值,并由此开始计算,不产生重复计算,则为On

代码:

java 复制代码
public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }

        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!set.contains(nums[i] - 1)) {
                int y = nums[i] + 1;
                while (set.contains(y)) {
                    y++;
                }
                max = Math.max(max, y-nums[i]);
            }
        }

        return max;
    }
相关推荐
virus59456 小时前
悟空CRM mybatis-3.5.3-mapper.dtd错误解决方案
java·开发语言·mybatis
一匹电信狗7 小时前
【LeetCode_547_990】并查集的应用——省份数量 + 等式方程的可满足性
c++·算法·leetcode·职场和发展·stl
鱼跃鹰飞7 小时前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
没差c8 小时前
springboot集成flyway
java·spring boot·后端
时艰.8 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
梵刹古音8 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
编程彩机8 小时前
互联网大厂Java面试:从Java SE到大数据场景的技术深度解析
java·大数据·spring boot·面试·spark·java se·互联网大厂
笨蛋不要掉眼泪8 小时前
Spring Boot集成LangChain4j:与大模型对话的极速入门
java·人工智能·后端·spring·langchain
筵陌9 小时前
算法:模拟
算法
Yvonne爱编码9 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python