LeetCode OJ - Longest Consecutive Sequence

来源:互联网 发布:如何套用淘宝商品模板 编辑:程序博客网 时间:2024/05/01 05:31

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.

分析:采用排序O(n * logn),在查找O(n),不符合题意。改变存储结构使用Hash表,使得查找变为O(1)

class Solution {public:    int longestConsecutive(vector<int> &num) {        if(num.size() == 0) return 0;        unordered_set<int> hash;        for(int i = 0; i < num.size(); i++) {            hash.insert(num[i]);        }        int ret = 1;        for(int i = 0; i < num.size(); i++) {            int count = 1;            int left = num[i] - 1;            int right = num[i] + 1;            while(hash.find(left) != hash.end()) {                hash.erase(left);                count++;                left--;            }            while(hash.find(right) != hash.end()) {                hash.erase(right);                count++;                right++;            }            ret = max(ret, count);        }        return ret;    }};

可在每次判断计数前判断if(hash.find(num[i]) == hash.end()) continue;省去不必要的计数

0 0
原创粉丝点击