zoukankan      html  css  js  c++  java
  • Leetcode(128) Longest Consecutive Sequence

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

    Your algorithm should run in O(n) complexity.

    Example:

    1
    2
    3
    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.

    解法

    补充以下,这题不用考虑数组中元素想等的情况,比如[1, 1, 1, 1]的输出为1。

    这题的方法有点难想,最后参考的网上的解法:

    使用一个集合HashSet存入所有的数字,然后遍历数组中的每个数字,如果其在集合中存在,那么将其移除,然后分别用两个变量pre和next算出其前一个数跟后一个数,然后在集合中循环查找,如果pre在集合中,那么将pre移除集合,然后pre再自减1,直至pre不在集合之中,对next采用同样的方法,那么next-pre-1就是当前数字的最长连续序列,更新res即可。这里再说下,为啥当检测某数字在集合中存在当时候,都要移除数字。这是为了避免大量的重复计算,就拿题目中的例子来说吧,我们在遍历到4的时候,会向下遍历3,2,1,如果都不移除数字的话,遍历到1的时候,还会遍历2,3,4。同样,遍历到3的时候,向上遍历4,向下遍历2,1,等等等。如果数组中有大量的连续数字的话,那么就有大量的重复计算,十分的不高效。

    具体代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26 大专栏  Leetcode(128) Longest Consecutive Sequence
    27
    28
    29
    30
    class  {
    public int longestConsecutive(int[] nums) {
    if(nums.length == 0){
    return 0;
    }
    HashSet<Integer> numSet = new HashSet();
    for(int x : nums){
    numSet.add(x);
    }
    int res = 1;
    for(int i = 0; i < nums.length; i++){
    if(!numSet.contains(nums[i])){
    continue;
    }
    numSet.remove(nums[i]);
    int pre = nums[i] - 1;
    int next = nums[i] + 1;
    while(numSet.contains(pre)){
    numSet.remove(pre);
    pre--;
    }
    while(numSet.contains(next)){
    numSet.remove(next);
    next++;
    }
    res = res > next - pre -1 ? res : next - pre -1;
    }
    return res;
    }
    }
  • 相关阅读:
    [爬虫] js
    [爬虫] appium-移动端
    如何进行代码的重构
    重写与覆盖的区别
    解决C#中FileSystemWatcher类的Changed事件触发多次的问题
    关于sqlserver 2008 远程导入表数据
    css 选择器
    前端三剑客
    前端的概述
    元类作业
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12371156.html
Copyright © 2011-2022 走看看