• 最长连续序列


    给定一个未排序的整数数组,找出最长连续序列的长度。

    要求算法的时间复杂度为 O(n)

    示例:

    输入: [100, 4, 200, 1, 3, 2]
    输出: 4
    解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。


    解析:
    可以把这道题想象成最大岛屿面积的那道题,就是求最大的连在一起的
    1、先把所有的数字都放进set中
    2、这个时候遍历数组,随便找到一个数字n,就在set中判断n-1在不在里面,再判断n-2 一直向左延伸,只要有就把这个数字去掉(最大岛屿那道题,遍历过的岛屿都要置为0),同理向右延伸
    那么当前n所能延伸到的最大长度为 左延伸 + 右延伸 + 1
    3、在遍历数组的过程中,一直更新最大值即可
    class Solution {
        public int longestConsecutive(int[] nums) {
            HashSet<Integer> set = new HashSet<>();
            int len = nums.length;
            int res = 0;
            for (int i = 0; i < len; i++) {
                set.add(nums[i]);
            }
            for (int i = 0; i < len; i++) {
                int left = 0;
                int right = 0;
                int from = nums[i];
                while (set.remove(--from)) {
                    left++;
                }
                from = nums[i];
                while (set.remove(++from)) {
                    right++;
                }
                res = Math.max(res, left + right + 1);
            }
            return res;
        }
    }
  • 相关阅读:
    实现PHP Thread基类
    完美实现PHP多线程
    Centos操作记录(一)
    Centos Minimal7 安装问题
    Server Git开发流程
    APP Git协作流程
    git学习笔记
    CentOS安装Nginx
    C++学习笔记(一)
    sql进阶:分组查询、子查询、连接查询
  • 原文地址:https://www.cnblogs.com/tobemaster/p/12404984.html
Copyright © 2020-2023  润新知