[LeetCode][Java] Longest Consecutive Sequence

來源:互聯網
上載者:User

標籤:leetcode   java   longest consecutive   

題目:

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.

題意:

給定一個未排序的整數數組,返回最長的連續元素的長度。

給定[100, 4, 200, 1, 3, 2],

最長連續元素序列為[1, 2, 3, 4].返回它的長度為:4.

你的演算法的複雜度應該為O(n) .

演算法分析:

   *  排序的話至少要O(nlgn) 的複雜度。

   *  O(n)的複雜度,目前只找到了使用hash來解決的方案,

   *  add, remove, contains 等方法的複雜度都是 O(1),因此兩次遍曆的操作複雜度為 O(n)。

    *  先把數字放到一個集合中,拿到一個數字,就往其兩邊搜尋,得到包含這個數位最長串,

    *  並且把用過的數字從集合中移除(因為連續的關係,一個數字不會出現在兩個串中)。最後比較當前串是不是比當前最大串要長,是則更新。

    * 如此繼續直到集合為空白。

    *  After an element is checked, it should be removed from the set.

    *  Otherwise, time complexity would be O(mn) in which m is the average length of all consecutive sequences.

AC代碼:

<span style="font-size:12px;">public static int longestConsecutive(int[] num)     {    // if array is empty, return 0    if (num.length == 0)     return 0;        Set<Integer> set = new HashSet<Integer>();    int max = 1;         for (int e : num)    set.add(e);         for (int e : num)     {    int left = e - 1;    int right = e + 1;    int count = 1;         while (set.contains(left))     {    count++;    set.remove(left);    left--;    }         while (set.contains(right))     {    count++;    set.remove(right);    right++;    }         max = Math.max(count, max);    }    return max;    }}</span>


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Longest Consecutive Sequence

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.