leetcode刷题,总结,记录,备忘 128

来源:互联网 发布:linux更改文件权限例子 编辑:程序博客网 时间:2024/05/16 17:01

leetcode128Longest Consecutive Sequence

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.

Subscribe to see which companies asked this question

我直接使用了c++的sort和unique两个函数,先排序,然后找出重复的部分并且去除,然后再自己循环遍历处理就非常简单了。但是排序的时间复杂度貌似是nlogn,,,,我也看了网上的使用map或者set的方法,,,但是提交不通过,,,而且我自己像出来的这个方法才16ms,也不是特别慢,,,

class Solution {public:    int longestConsecutive(vector<int>& nums) {        if (nums.size() == 0)        {            return 0;        }                if (nums.size() == 1)        {            return 1;        }                sort(nums.begin(), nums.end());        nums.erase(unique(nums.begin(), nums.end()), nums.end());                int len = 1;        int maxlen = 1;        for (vector<int>::iterator it = nums.begin(); it != nums.end() - 1; ++it)        {           if (*it + 1 == *(it + 1))           {               len++;           }           else           {               if (len > maxlen)               {                   maxlen = len;               }                 len = 1;           }        }                if (len > maxlen)        maxlen = len;                return maxlen;    }};


0 0
原创粉丝点击