zoukankan      html  css  js  c++  java
  • 0128. Longest Consecutive Sequence (M)

    Longest Consecutive Sequence (M)

    题目

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

    You must write an algorithm that runs in O(n) time.

    Example 1:

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

    Example 2:

    Input: nums = [0,3,7,2,5,8,4,6,0,1]
    Output: 9 
    

    Constraints:

    • 0 <= nums.length <= 10^5
    • -10^9 <= nums[i] <= 10^9

    题意

    给定一个数组,从中选择若干数字组成序列,使该序列中的数字依次递增加一,求满足的最长的序列。

    思路

    O(N)方法:先将所有数存入HashSet中,利用HashSet找到每一个满足序列的第一个数字(即找到数字num,使得num在set中,但num-1不在set中),从该数字出发求出整个序列的长度。实际上每个数字被访问了两次,复杂度为O(N)。


    代码实现

    Java

    class Solution {
        public int longestConsecutive(int[] nums) {
            int ans = 0;
            Set<Integer> set = new HashSet<>();
    
            for (int num : nums) {
                set.add(num);
            }
    
            for (int num : set) {
                if (set.contains(num - 1)) continue;
    
                int cnt = 1;
                while (set.contains(num + 1)) {
                    cnt++;
                    num++;
                }
    
                ans = Math.max(ans, cnt);
            }
    
            return ans;
        }
    }
    
  • 相关阅读:
    最小生成数kruskal算法和prim算法
    图的表示及遍历
    mysql忘记root用户密码重置密码的方式
    dwr2.0版本的demo
    web.xml中不同版本的servlet头以及版本控制
    初学jboss
    Filter学习总结,顺便提及点servlet3.0异步filter和异步监听
    监听器
    问题发现和解决
    linux学习
  • 原文地址:https://www.cnblogs.com/mapoos/p/14856468.html
Copyright © 2011-2022 走看看