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;
        }
    }
  • 相关阅读:
    Java学习开篇
    《我的姐姐》
    世上本无事,庸人自扰之
    这48小时
    补觉
    淡定
    es java api 设置index mapping 报错 mapping source must be pairs of fieldnames and properties definition.
    java mongodb groupby分组查询
    linux 常用命令
    mongodb too many users are authenticated
  • 原文地址:https://www.cnblogs.com/silentteller/p/12357318.html
Copyright © 2011-2022 走看看