LeetCode 刷题【128. 最长连续序列】

128. 最长连续序列

自己做

解1:排序

java 复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums.length == 0)
            return 0;

        //排序
        Arrays.sort(nums);

        int max = 1;
        int len = 1;

        for(int i = 1; i < nums.length; i++){
            if(i > 1 && nums[i] == nums[i - 1])
                nums[i - 1] = nums[i - 2];
            else if(nums[i] == nums[i - 1] + 1)
                len++;
            else
                len = 1;

            if(len > max)
                max = len;
        }

        return max;
    }
}

看题解

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

        int longestStreak = 0;

        for (int num : num_set) {
            if (!num_set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                while (num_set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }
}
相关推荐
ShineWinsu1 天前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
DuHz1 天前
基于时频域霍夫变换的汽车雷达互干扰抑制——论文阅读
论文阅读·算法·汽车·毫米波雷达
hetao17338371 天前
ZYZ28-NOIP模拟赛-Round4 hetao1733837的record
c++·算法
Nebula_g1 天前
C语言应用实例:解方程(二分查找)
c语言·开发语言·学习·算法·二分查找·基础
少许极端1 天前
算法奇妙屋(十)-队列+宽搜(BFS)
java·数据结构·算法·bfs·宽度优先·队列
前端架构师-老李1 天前
进入职场第二课—融入
程序人生·职场和发展
想唱rap1 天前
Linux开发工具(4)
linux·运维·服务器·开发语言·算法
前端炒粉1 天前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
星释1 天前
Rust 练习册 :Rail Fence Cipher与栅栏密码
开发语言·算法·rust