zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    好文章集合
    WPF:布局
    xcode6.0 模拟器打不开
    vue-vux初学
    【个人笔记】《知了堂》MySQL三种关系:一对一,一对多,多对多。
    vue-axios跨域配置
    vue+webpack使用
    vs code插件
    echarts图表属性设置
    【个人笔记】《知了堂》ajax的get及post请求
  • 原文地址:https://www.cnblogs.com/feiling/p/3252583.html
Copyright © 2011-2022 走看看