LeetCode 128. Longest Consecutive Sequence

/**
  Given an unsorted array of integer, find the length of the longest
  consecutive elements sequence.
  For example:
  Given [100, 4, 200, 1, 3, 2]
  The longest consecutive element is [1, 2, 3, 4]. Return its length: 4
  Your algorithm should run in O(n) complexity.
**/
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

int longConsecutive(vector<int>& nums) {
  if(nums.size() <= 1) return nums.size();
  unordered_set<int> data;
  int maxLength = 0;
  for(int i= 0; i < nums.size(); ++i) {
    data.insert(nums[i]);
  }
  for(int i = 0; i < nums.size(); ++i) {
    int target = nums[i];
    int right = target + 1;
    int left = target - 1;
    int count = 1;
    while(true) {
      if(data.find(right) != data.end()) {
        data.erase(right);
        right = right + 1;
        count++;
      } else {
        break;
      }
    }
    while(true) {
      if(data.find(left) != data.end()) {
        data.erase(left);
        left = left - 1;
        count++;
      } else {
        break;
      }
    }
    maxLength = max(maxLength, count);
  }
  return maxLength;
}

int main(void) {
  vector<int> array;
  array.push_back(100);
  array.push_back(1);
  array.push_back(2);
  array.push_back(4);

int length = longConsecutive(array);
cout << length << endl;
}

你可能感兴趣的:(LeetCode 128. Longest Consecutive Sequence)