zoukankan      html  css  js  c++  java
  • LeetCode 128. Longest Consecutive Sequence 最长连续序列 (C++/Java)

    题目:

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

    Your algorithm should run in O(n) complexity.

    Example:

    Input: [100, 4, 200, 1, 3, 2]
    Output: 4
    Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

    分析:

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

    可以先对数组进行排序,然后遍历数组,判断数字是否连续来计算最大长度,不过由于排序,时间复杂度是O(nlogn),我们可以利用哈希表来存储数组元素,再遍历元素,当前元素为num时,如果num-1这个元素不在我们的集合中,就代表这个num可以作为序列的起始点,然后依次判断num++是否在集合中,更新当前序列最大长度,当出现num++不在集合中,也就是此时序列不再连续,更新全局最大长度,继续遍历数组,最后返回全局的最大长度即可。

    程序:

    C++

    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            unordered_set<int> set(nums.begin(), nums.end());
            int res = 0;
            for(int num:nums){
                if(!set.count(num-1)){
                    int l = 1;
                    while(set.count(++num)){
                        l++;
                    }
                    res = max(res, l);
                }
            }
            return res;
        }
    };

    Java

    class Solution {
        public int longestConsecutive(int[] nums) {
            if(nums.length == 0)
                return 0;
            int res = 0;
            Set<Integer> set = new HashSet<>();
            for(int num:nums)
                set.add(num);
            for(int num:nums){
                if(!set.contains(num-1)){
                    int l = 1;
                    while(set.contains(++num))
                        l++;
                    res = Math.max(l, res);
                }
            }
            return res;
        }
    }
  • 相关阅读:
    构造并判断二叉搜索树-js
    构造树并判断是否对称
    旋转图像
    螺旋矩阵
    链表实现快速排序
    任务调度器
    队列的实现
    最大矩形
    棒球比赛
    复原IP地址
  • 原文地址:https://www.cnblogs.com/silentteller/p/12357318.html
Copyright © 2011-2022 走看看