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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

LeetCode 128. Longest Consecutive Sequence

2019-11-14 12:07:08
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

描述 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) 的復(fù)雜度,那么可以先排序,可是本題要求 O(n)。 由于序列里的元素是無(wú)序的,又要求 O(n),首先要想到用哈希表。 用一個(gè)哈希表 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; }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 濉溪县| 乌拉特后旗| 永靖县| 梅河口市| 孝昌县| 常德市| 龙门县| 永安市| 塘沽区| 潮安县| 阿巴嘎旗| 平度市| 宜都市| 蒲城县| 旅游| 平遥县| 玉门市| 蓬溪县| 南华县| 怀仁县| 龙里县| 孟津县| 鄂托克旗| 罗江县| 鞍山市| 望谟县| 绥中县| 定陶县| 清新县| 临西县| 贡山| 保德县| 临泉县| 前郭尔| 公主岭市| 长阳| 庆元县| 乐山市| 德令哈市| 巴马| 平定县|