leetcode Longest Consecutive Sequence
2015-12-09 20:15
483 查看
原题链接:https://leetcode.com/problems/longest-consecutive-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.
Description
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 { private: typedef vector<int> vec; typedef unordered_map<int, bool> UMAP; public: int longestConsecutive(vec &nums) { if(nums.empty()) return 0; UMAP vis; int ans = 0; for(auto &r: nums) vis[r] = false; for(auto &r: nums) { if(vis[r]) continue; int ret = 1; vis[r] = true; for(int j = r + 1; vis.find(j) != vis.end(); j++) { vis[j] = true; ret++; } for(int j = r - 1; vis.find(j) != vis.end(); j--) { vis[j] = true; ret++; } ans = max(ans, ret); } return ans; } };
相关文章推荐
- Error:ERROR ITMS-90474: "Invalid Bundle. iPad Multitasking support requires these orientations:
- Could not execute JDBC batch update : java.sql.BatchUpdateException: ORA-00926: 缺失 VALUES 关键字
- UE4连接Oculuse DK2设备
- UGUI之页面滑动(Grid Layout和Scorll Rect&&mask)
- [leetcode]Unique Paths II
- [leetcode]Unique Paths
- Exception:exception setting property value with CGLIB
- UISearchDisplayController简单使用
- spannableStringBuilder 用法详解
- SpannableString与SpannableStringBuilder
- UIView常用的一些方法
- POJ 1019 number sequece数学处理
- 快速排序算法(QuickSort)
- iOS UIProgressView 的progress属性 在循环中赋值无效 解决方案
- 本地推送UILocalNotification(整理)
- UI/UIWindow/UIView
- 通过UIEdgeInsetsMake来制作可伸缩的Button(图片拉伸)
- zzulioj 1801: xue姐的小动物 (排序)水
- UEFI启动模式安装ubuntu指南
- iOS点击UITableView的cell,弹出UIAlertController有时会出现延迟