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;
        }
    }
  • 相关阅读:
    大型网站架构
    大数据以及Hadoop相关概念介绍
    Hadoop产生背景
    hadoop知识体系
    hadoop生态系统
    大数据工具集详
    大数据工具集
    关于CoDeSys OPC ua配置的记录
    我要去做it培训讲师了
    用C#将Excel中的数据写入到DataSet中
  • 原文地址:https://www.cnblogs.com/yanhowever/p/11908420.html
Copyright © 2011-2022 走看看