Longest Consecutive Sequence

原创 2016年08月31日 15:19:00

一、问题描述

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.

二、思路

本题题意是求出最大的连续序列的长度。我们先对数组排序,然后遍历整个数组,遇到相同元素,跳过,遇到满足连续特性的数组,我们将临时变量加一,遇到不满足条件的元素,我们首先判断当前临时变量是否大于等于最大长度,如果满足,则更新max_len,同时不管是否满足条件都将临时变量置一,意味着重新开始。最后挑出循环后继续判断临时变量是否大于最大长度,如果大于,则需要更新最大长度。

三、代码

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


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LeetCode with Python】 Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. ...
  • nerv3x3
  • nerv3x3
  • 2014年07月06日 15:09
  • 2737

【LeetCode】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. ...

Array(12) -- Longest Consecutive Sequence, First Missing Positive, Buy and Sell Stock III, Find Mini

Longest Consecutive Sequence,First Missing Positive, Best Time to Buy and Sell Stock III, Find Minim...
  • dwt0317
  • dwt0317
  • 2017年01月04日 16:09
  • 71

Longest Consecutive Sequence--LeetCode

题目: Given an unsorted array of integers, find the length of the longest consecutive elements sequen...

154. Find Minimum in Rotated Sorted Array II \ 128. Longest Consecutive Sequence

Find Minimum in Rotated Sorted Array II 题目解析 代码实现154. Find Minimum in Rotated Sorted Array II题目解析Sup...

Longest Consecutive Sequence(LeetCode)

题目: 思路: 注意点: 代码:

LeetCode Algorithms 128. Longest Consecutive Sequence 题解

Given an unsorted array of integers, find the length of the longest consecutive elements sequence...

[LeetCode]128.Longest Consecutive Sequence

Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longes...

leetcode之longest-consecutive-sequence

问题描述: Given an unsorted array of integers, find the length of the longest consecutive elements seq...
  • zjwcdd
  • zjwcdd
  • 2016年05月25日 19:44
  • 152

[LeetCode][Java] Longest Consecutive Sequence

题目: Given an unsorted array of integers, find the length of the longest consecutive elements se...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Longest Consecutive Sequence
举报原因:
原因补充:

(最多只允许输入30个字)