LeetCode 128. Longest Consecutive Sequence
2016-04-08 11:08
555 查看
/** Given an unsorted array of integer, find the length of the longest consecutive elements sequence. For example: Given [100, 4, 200, 1, 3, 2] The longest consecutive element is [1, 2, 3, 4]. Return its length: 4 Your algorithm should run in O(n) complexity. **/ #include <iostream> #include <vector> #include <unordered_set> using namespace std; int longConsecutive(vector<int>& nums) { if(nums.size() <= 1) return nums.size(); unordered_set<int> data; int maxLength = 0; for(int i= 0; i < nums.size(); ++i) { data.insert(nums[i]); } for(int i = 0; i < nums.size(); ++i) { int target = nums[i]; int right = target + 1; int left = target - 1; int count = 1; while(true) { if(data.find(right) != data.end()) { data.erase(right); right = right + 1; count++; } else { break; } } while(true) { if(data.find(left) != data.end()) { data.erase(left); left = left - 1; count++; } else { break; } } maxLength = max(maxLength, count); } return maxLength; } int main(void) { vector<int> array; array.push_back(100); array.push_back(1); array.push_back(2); array.push_back(4); int length = longConsecutive(array); cout << length << endl; }
相关文章推荐
- ubuntu下打印unit64_t size_t uint32_t 类型
- xoyojank 的 UE4中的DynamicTexture数据更新
- [IOS 开发] 获取设备UUID
- UINavigationBar的视图层级关系
- iOS---[UIDevice identifierForVendor]慎用!
- Qt 示例学习--2. calendar quick controls
- ios GPUImage简单滤镜 -- 录制视频(保存+聚焦)
- android 开发,百度地图 UI 控制器常用方法及作用
- UITabView使用详解
- LeetCode *** 232. Implement Queue using Stacks
- requirejs和r.js的心得
- 重写的easyui-validatebox 验证规则
- UI 常用(UIButton)
- easyui-validatebox form表单提交时校验 ajax提交时校验
- Android中的requestWindowFeature()函数
- 去掉UItableview headerview黏性
- 如何现实隐藏UIBarButtonItem? show/hide a UIBarButtonItem
- Building VirtualBox OSE 5.0.0 on Windows 7 (x86)
- Strtus2——request、response等内置对象的获取方式
- 解决AndroidStduio出现merger failed with multiple errors, see logs