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

LeetCode-128. Longest Consecutive Sequence

https://leetcode.com/problems/longest-consecutive-sequence/description/

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.

題解:邊界值坑死了。。。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
      int n = nums.size();
      if (n <= 1){
        return n;
      }
      int ans = 1, l = 1;
      sort(nums.begin(), nums.end());
      for (int i = 0; i < n - 1; i++){
        if (nums[i] == nums[i + 1] - 1){
          l++;
        }
        else if (nums[i] == nums[i + 1]){
          continue;
        }
        else {
          l = 1;
        }
        ans = max(ans, l);
      }
      return ans;
    }
};