[LeetCode] Longest Consecutive Sequence 求最長連續序列
阿新 • • 發佈:2018-12-27
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.
這道題要求求最長連續序列,並給定了O(n)複雜度限制,我們的思路是,使用一個集合set存入所有的數字,然後遍歷陣列中的每個數字,如果其在集合中存在,那麼將其移除,然後分別用兩個變數pre和next算出其前一個數跟後一個數,然後在集合中迴圈查詢,如果pre在集合中,那麼將pre移除集合,然後pre再自減1,直至pre不在集合之中,對next採用同樣的方法,那麼next-pre-1就是當前數字的最長連續序列,更新res即可。程式碼如下:
C++ 解法一:
class Solution { public: int longestConsecutive(vector<int>& nums) { int res = 0; unordered_set<int> s(nums.begin(), nums.end()); for (int val : nums) { if (!s.count(val)) continue; s.erase(val); intpre = val - 1, next = val + 1; while (s.count(pre)) s.erase(pre--); while (s.count(next)) s.erase(next++); res = max(res, next - pre - 1); } return res; } };
Java 解法一:
public class Solution { public int longestConsecutive(int[] nums) { int res = 0; Set<Integer> s = new HashSet<Integer>(); for (int num : nums) s.add(num); for (int num : nums) { if (s.remove(num)) { int pre = num - 1, next = num + 1; while (s.remove(pre)) --pre; while (s.remove(next)) ++next; res = Math.max(res, next - pre - 1); } } return res; } }
我們也可以採用雜湊表來做,剛開始雜湊表為空,然後遍歷所有數字,如果該數字不在雜湊表中,那麼我們分別看其左右兩個數字是否在雜湊表中,如果在,則返回其雜湊表中對映值,若不在,則返回0,然後我們將left+right+1作為當前數字的對映,並更新res結果,然後更新d-left和d-right的對映值,參見程式碼如下:
C++ 解法二:
class Solution { public: int longestConsecutive(vector<int>& nums) { int res = 0; unordered_map<int, int> m; for (int d : nums) { if (!m.count(d)) { int left = m.count(d - 1) ? m[d - 1] : 0; int right = m.count(d + 1) ? m[d + 1] : 0; int sum = left + right + 1; m[d] = sum; res = max(res, sum); m[d - left] = sum; m[d + right] = sum; } } return res; } };
Java 解法二:
public class Solution { public int longestConsecutive(int[] nums) { int res = 0; Map<Integer, Integer> m = new HashMap<Integer, Integer>(); for (int num : nums) { if (m.containsKey(num)) continue; int left = m.containsKey(num - 1) ? m.get(num - 1) : 0; int right = m.containsKey(num + 1) ? m.get(num + 1) : 0; int sum = left + right + 1; m.put(num, sum); res = Math.max(res, sum); m.put(num - left, sum); m.put(num + right, sum); } return res; } }
類似題目:
參考資料: