標籤: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