zoukankan      html  css  js  c++  java
  • Leetcode#128 Longest Consecutive Sequence

    原题地址

    1. 把所有元素都塞到集合里
    2. 遍历所有元素,对于每个元素,如果集合里没有,就算了,如果有的话,就向左向右拓展,找到最长的连续范围,同时在每次找的时候都把找到的删掉。这样做保证了同样的连续序列只会被遍历一次,从而保证时间复杂度。

    时间复杂度O(n)

    代码:

     1 int longestConsecutive(vector<int> &num) {
     2   set<int> record;
     3   int maxLength = 0;
     4 
     5   for (auto n : num)
     6     record.insert(n);
     7 
     8   while (!record.empty()) {
     9     int len = 1;
    10     int n = *(record.begin());
    11     record.erase(n);
    12     for (int i = n - 1; record.find(i) != record.end(); i--) {
    13       len++;
    14       record.erase(i);
    15     }
    16     for (int i = n + 1; record.find(i) != record.end(); i++) {
    17       len++;
    18       record.erase(i);
    19     }
    20     maxLength = max(maxLength, len);
    21   }
    22 
    23   return maxLength;
  • 相关阅读:
    JavaWeb 【介绍】
    Python3 【解析库XPath】
    Python【类编程】
    Python3【正则表达式】
    Java GUI【记事本】
    Java 【笔记本】
    Python3 【requests使用】
    Java 【食品库存管理】
    AGC027 C
    AGC027 A
  • 原文地址:https://www.cnblogs.com/boring09/p/4236402.html
Copyright © 2011-2022 走看看