leetcode 128: Longest Consecutive Sequence
2015-08-16 21:21
567 查看
Use the unordered set which has the O(1) time complexity when accessing one number. The key here is to update the max only when I find one number is the left most number in one range.
Updated version. Find the maximum range for one number and erase all numbers visited.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> numSet;
int size=nums.size();
for(int i=0;i<size;i++)
numSet.insert(nums[i]);
unordered_set<int>::iterator it;
int res=0;
for(it=numSet.begin();it!=numSet.end();it++)
{
int l=*it,r=*it;
while(numSet.find(l-1)!=numSet.end())
{
numSet.erase(l-1);
l--;
}
while(numSet.find(r+1)!=numSet.end())
{
numSet.erase(r+1);
r++;
}
if(r-l+1>res)
res=r-l+1;
}
return res;
}
};
class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_set<int> set; for(int i=0;i<nums.size();i++) set.insert(nums[i]); int max=0; unordered_set<int>::iterator it; for(it=set.begin();it!=set.end();it++) { int num=*it; if(set.find(num-1)==set.end()) { while(set.find(num+1)!=set.end()) num++; if(num-*it+1>max) max=num-*it+1; } } return max; } };
Updated version. Find the maximum range for one number and erase all numbers visited.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> numSet;
int size=nums.size();
for(int i=0;i<size;i++)
numSet.insert(nums[i]);
unordered_set<int>::iterator it;
int res=0;
for(it=numSet.begin();it!=numSet.end();it++)
{
int l=*it,r=*it;
while(numSet.find(l-1)!=numSet.end())
{
numSet.erase(l-1);
l--;
}
while(numSet.find(r+1)!=numSet.end())
{
numSet.erase(r+1);
r++;
}
if(r-l+1>res)
res=r-l+1;
}
return res;
}
};
相关文章推荐
- 最长上升子序列 LIS(Longest Increasing Subsequence)(转)
- 1151 - Buy or Build (最小生成树)
- 机房合作总结
- HDU 5301(Buildings-贪心构造)
- iOS UI 视图移动及缩放
- Codeforce466A——贪心——DZY Loves Sequences
- HDU 2227-Find the nondecreasing subsequences(dp+BIT优化)
- <input value="hidden">的作用
- iOS 8_UIAlertController
- UIView管理子视图
- Common Subsequence LCS
- Common Subsequence
- 加载资源文件的三种方式
- DAV request failed解决方法
- 【转】Windows和Ubuntu双系统,修复UEFI引导的两种办法
- 解决git提交问题error: The requested URL returned error: 403 Forbidden while accessing
- codeforces 570 D. Tree Requests (dfs)
- 读《How quitting...》有感
- EasyUI----DataGrid 导出 Excel
- UIScrollView 实践经验