zoukankan      html  css  js  c++  java
  • leetcode 128. 最长连续序列 java

    题目:

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

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

    示例:

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

    解题:

    class Solution {
        public int longestConsecutive(int[] nums) {
            //空间换时间
            Set<Integer> numsSet = new HashSet<>();
            for (Integer num : nums) {
                numsSet.add(num);
            }
            int longest = 0;
            for (Integer num : nums) {
                if (numsSet.remove(num)) {
                    // 向当前元素的左边搜索,eg: 当前为100, 搜索:99,98,97,...
                    int currentLongest = 1;
                    int current = num;
                    while (numsSet.remove(current - 1)) current--;
                    currentLongest += (num - current);
                    // 向当前元素的右边搜索,eg: 当前为100, 搜索:101,102,103,...
                    current = num;
                    while(numsSet.remove(current + 1)) current++;
                    currentLongest += (current - num);
                    // 搜索完后更新longest.
                    longest = Math.max(longest, currentLongest);
                }
            }
            return longest;
        }
    }
  • 相关阅读:
    Go 数组与切片
    Go 常用函数
    Go 函数,包(二)
    函数,包及错误处理
    Go 循环控制
    Go 流程控制
    Go 获取键盘输入,进制转换
    Go 指针,标识符命名规范及关键字
    Go 变量及基本数据类型3
    一文详解微服务架构
  • 原文地址:https://www.cnblogs.com/yanhowever/p/11908420.html
Copyright © 2011-2022 走看看