1. 程式人生 > >【LeetCode】128. Longest Consecutive Sequence

【LeetCode】128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

0 、題目分析

我們可以使用unordered_set和map兩種STL來獲取最長連續序列長度

1、map

  1. 首先我們定義一個空map
  2. 接著我們遍歷每一個數字num
    1. 如果這個數字num不在map裡面,即map[num]==0,我們就開始遍歷它的左右,即num-1,num+1
    2. 如果num-1在map裡面,即LeftValue = map[num-1]>0,如果不在,我們取LeftValue=0
    3. 同理取RightValue
    4. 將map[num],map[num - LeftValue]和map[num - RightValue]賦值為LeftValue + RightValue + 1
    5. 將res更新為max(res,LeftValue + RightValue + 1)
    6. 如果這個數字num在map裡面,說明它已經被遍歷過,因此不做任何操作
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int res = 0;
        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; } };

2、set

  1. 首先把nums儲存到unordered_set裡面
  2. 然後遍歷每一個數字num
    1. 如果num在set裡面,那麼遍歷num-1和num+2,直到num-left-1和num+right+1不在set裡面
    2. 將res更新為max(res,right+left+1)
    3. 每一次查詢成功時,需要把這個數字從set中刪除,因為它已經不需要被查詢,可以減少查詢的複雜度
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);
            int pre = 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;
    }
};