• leetcode -- Longest Consecutive Sequence


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

    For example,
    Given [100, 4, 200, 1, 3, 2],
    The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

    Your algorithm should run in O(n) complexity.

    large data TLE

     1 public class Solution {
     2     public int longestConsecutive(int[] num) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int result = 0;
     6         HashSet<Integer> con = new HashSet<Integer>();
     7         for(int i = 0; i < num.length; i++){
     8             int tmpLen = 1;
     9             int val = num[i];
    10             con.add(val);
    11             while(con.contains(--val)){
    12                 tmpLen ++;
    13             }
    14             val = num[i];
    15             while(con.contains(++val)){
    16                 tmpLen ++;
    17             }
    18             
    19             if(tmpLen > result){
    20                 result = tmpLen;
    21             }
    22         }
    23         
    24         return result;
    25     }
    26 }

     refactor:

    1.使用HashSet来去重

    2.遍历数组,循环查看每个元素的相邻元素:

    i.检查num-1是否在Set中(loop),如在则从Set中去除

    i.检查num+1是否在Set中(loop),如在则从Set中去除

     1 public int longestConsecutive(int[] num) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         int result = 0;
     5         HashSet<Integer> con = new HashSet<Integer>();
     6         for(int i = 0; i < num.length; i++){
     7             con.add(num[i]);
     8         }
     9         
    10         for(int i = 0; i < num.length; i++){
    11             int tmpLen = 1;
    12             int val = num[i];
    13             while(con.contains(--val)){
    14                 con.remove(val);                
    15                 tmpLen ++;
    16             }
    17             val = num[i];
    18             while(con.contains(++val)){
    19                 con.remove(val);
    20                 tmpLen ++;
    21             }
    22             con.remove(num[i]);
    23             
    24             if(tmpLen > result){
    25                 result = tmpLen;
    26             }
    27         }
    28         
    29         return result;
    30     }
  • 相关阅读:
    ubuntu frp 自编译。本文不能按顺序来 请自己理解
    油猴子 自改脚本 删除页面 div 上下翻页 视频页内全屏 右键可用
    批处理bat 删除指定文件夹下的文件及文件夹
    LUA 静态库 动态库 LD_LIBRARY_PATH 动态库的查找路径 GCC “-l”参数
    delphi 判断奇数偶数
    sf.net
    cmake指定mingw编译器的方法
    关闭delphi ide皮肤
    arch pacman被删除 重装
    delphi 匿名方法访问var参数
  • 原文地址:https://www.cnblogs.com/feiling/p/3252583.html
Copyright © 2020-2023  润新知