[leetcode]Longest Consecutive Sequence

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   資料   for   

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.

【注意】:這道題有幾個坑:

坑1:數組元素可能重複,比如-1,0,0,1,2.本以為重複就不算聯絡,答案應該是3,結果是4。你妹的

坑2:允許負數,這個沒考慮實在不應該。

坑3:大數可能是Integer.MIN_VALUE,因此用計數排序的時候要注意考慮溢出

 

演算法思路:

思路1:計數排序;線性排序演算法,再求出最長連續序列長度。

沒有做到bug-free,因此不貼了。

思路2:發散法,遇到一個數字,則想兩端發散,並維護最大長度。

 1 public class Solution {     2     public int longestConsecutive(int[] num) { 3         if (num == null || num.length == 0) 4             return 0; 5         Set<Integer> set = new HashSet<Integer>(); 6         int max = 1; 7         for (int tem : num) { 8             set.add(tem); 9         }10         for (int tem : num) {11             if (set.contains(tem)) {12                 set.remove(tem);13                 int len = 1;14                 int post = tem + 1;15                 while (set.contains(post)) {16                     set.remove(tem);17                     post++;18                     len++;19                     max = Math.max(max, len);20                 }21                 int pre = tem - 1;22                 while (set.contains(pre)) {23                     set.remove(pre);24                     pre--;25                     len++;26                     max = Math.max(max, len);27                 }28             }29         }30         return max;31     }32 33 }

還可以用遞迴實現。大資料效率略低,不再實現了。時間、空間複雜度都是O(n)。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.