首页 > 其他 > 详细

LeetCode-128-Longest Consecutive Sequence

时间:2019-02-17 19:49:53      阅读:306      评论:0      收藏:0      [点我收藏+]

算法描述:

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.

解题思路:时间复杂度要求O(n),首先想到hash。

    int longestConsecutive(vector<int>& nums) {
        if(nums.size()==0) return 0;
        unordered_map<int, int> map;
        for(int i =0 ; i < nums.size(); i++){
            map[nums[i]]++;
        }
        int maxLength = 0;
        for(int i=0; i < nums.size(); i++){
            int left = nums[i]-1;
            int right = nums[i]+1;
            while(right < INT_MAX && map.find(right)!=map.end()){
                map.erase(right++);
            }
            while(left > INT_MIN && map.find(left)!=map.end()){
                map.erase(left--);
            }
            maxLength = max(maxLength,right - left -1);
        }
        return maxLength;
    }

 

LeetCode-128-Longest Consecutive Sequence

原文:https://www.cnblogs.com/nobodywang/p/10392164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!