• Longest Consecutive Sequence 解答


    Question

    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.

    Solution

    一开始尝试用segment tree, heap等,发现时间复杂度不能达到线性。

    后来参考别人答案,发现用HashSet计数的方法。

    程序比较简单。

    1. 遍历一遍数组,将所有元素存入set

    2. 遍历数组。对于当前元素x,看x+1和x-1是否在set中。如果在,则remove,并且一直找到这个区间的边界。

     1 public class Solution {
     2     public int longestConsecutive(int[] nums) {
     3         Set<Integer> set = new HashSet<Integer>();
     4         for (int i : nums) {
     5             set.add(i);
     6         }
     7         int max = 0;
     8         int count;
     9         for (int i : nums) {
    10             if (set.isEmpty()) {
    11                 break;
    12             }
    13             count = 1;
    14             int right = i + 1;
    15             int left = i - 1;
    16             set.remove(i);
    17             // find right
    18             while (set.contains(right)) {
    19                 set.remove(right);
    20                 count++;
    21                 right++;
    22             }
    23             // find left
    24             while (set.contains(left)) {
    25                 set.remove(left);
    26                 count++;
    27                 left--;
    28             }
    29             max = Math.max(max, count);
    30         }
    31         return max;
    32     }
    33 }
  • 相关阅读:
    python路径相关
    python之json
    python之正则表达式备忘
    MD5 SHA1 HMAC HMAC_SHA1区别
    微信根据openid给用户发送图文消息
    最近做的几个小程序
    5000万pv小程序,高并发及缓存优化,入坑
    小程序 后台发送模板消息
    mysql 组合索引
    php 拆分txt小说章节保存到数据库
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4944713.html
Copyright © 2020-2023  润新知