• 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     }
  • 相关阅读:
    Bean管理学习笔记
    Spring核心概念学习笔记
    Spring主要用到两种设计模式
    C# 值类型和引用类型等值判断
    嵌入式Linux之gdb配置和使用
    嵌入式Linux之telnet
    构建嵌入式Linux交叉编译工具链
    Linux动态库和静态库
    VxWorks BSP开发入门
    buildroot
  • 原文地址:https://www.cnblogs.com/feiling/p/3252583.html
Copyright © 2020-2023  润新知