• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
128. Longest Consecutive Sequence *HARD* -- 寻找无序数组中最长连续序列的长度

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.

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int n = nums.size(), maxi = 0, cnt, i, k;
        if(n <= 0)
            return 0;
        unordered_set<int> numsSet;
        for(i = 0; i < n; i++)
        {
            numsSet.insert(nums[i]);
        }
        for(i = 0; i < n; i++)
        {
            cnt = 1;
            numsSet.erase(nums[i]);
            for(k = nums[i]+1; numsSet.find(k) != numsSet.end(); k++)
            {
                cnt++;
                numsSet.erase(k);
            }
            for(k = nums[i]-1; numsSet.find(k) != numsSet.end(); k--)
            {
                cnt++;
                numsSet.erase(k);
            }
            if(cnt > maxi)
                maxi = cnt;
        }
        return maxi;
    }
};

先遍历数组,把所有元素放到一个set中。

然后再遍历数组,对每个元素,在set中找比它大的连续数字和比它小的连续数字,若找到则计数器加一,同时从set中删除这个数字。

posted on 2016-05-08 10:04  ArgenBarbie  阅读(347)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3