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
.codeYour algorithm should run in O(n) complexity.排序
時間 O(NlogN) 空間 O(1)element
將數組排序後,從前向後遍歷,找到最長的連續部分,該方法隨不符合題意,可是不用空間。rem
時間 O(N) 空間 O(N)it
將全部數都加入集合中,而後再遍歷這些數,由於咱們能O(1)的判斷某個數是否在集合中,因此咱們能夠一個個向上或者向下檢查。爲了不以後重複檢查,咱們每查到一個數,都要將其從集合中移除。這樣每遇到一個數,都檢查它的上下邊界,就能找出最長的連續數列。時間複雜度還是O(N),由於咱們不會檢查不存在於數組的數,而存在於數組的數也只會檢查一次。io
public class Solution { public int longestConsecutive(int[] nums) { int maxlen = 0; Set<Integer> set = new HashSet<Integer>(); // 先將全部數字加入數組中 for(int n : nums){ set.add(n); } // 對於每一個數咱們都在集合中一一檢查它的上下邊界 for(int n : nums){ // 暫存n,供檢查下邊界時使用 int curr = n, len = 0; // 一個一個檢查上邊界 while(set.contains(curr)){ curr++; len++; set.remove(curr); } // 一個一個檢查下邊界 curr = n - 1; while(set.contains(curr)){ curr--; len++; set.remove(curr); } maxlen = Math.max(len, maxlen); } return maxlen; } }