国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode 128. Longest Consecutive Sequence

2019-11-14 12:07:32
字體:
來源:轉載
供稿:網友

描述 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 log n) 的復雜度,那么可以先排序,可是本題要求 O(n)。 由于序列里的元素是無序的,又要求 O(n),首先要想到用哈希表。 用一個哈希表 unordered_map

class Solution {public: int longestConsecutive(vector<int>& nums) { unordered_map<int, bool> used; for (auto i : nums) used[i] = false; int longest = 0; for (auto i : nums) { if (used[i] == true) continue; int length = 1; used[i] = true; for (int j = i + 1; used.find(j) != used.end(); ++j) { used[j] = true; ++length; } for (int j = i - 1; used.find(j) != used.end(); --j) { used[j] = true; ++length; } longest = (length < longest) ? longest : length; } return longest; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 磐石市| 平邑县| 临沧市| 特克斯县| 甘孜县| 兰坪| 谢通门县| 白玉县| 盐池县| 任丘市| 黄大仙区| 金阳县| 进贤县| 天柱县| 台湾省| 石柱| 沙雅县| 茂名市| 错那县| 龙山县| 苏州市| 刚察县| 永川市| 邯郸县| 江阴市| 雷波县| 育儿| 栖霞市| 邵阳县| 舒兰市| 阿拉善盟| 礼泉县| 大安市| 铁力市| 蒙城县| 江源县| 如皋市| 安泽县| 怀远县| 舞阳县| 聂拉木县|