标签:longest consecutive set map
Longest Consecutive Sequence
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
.
寻找最大的连续数组的长度,利用两个set数组,一个数组存储已经被访问过的数组,如果已经被访问过了,那么就不需要再被访问了
class Solution { public: int longestConsecutive(vector<int>& nums) { if(nums.empty()) { return 0; } unordered_set<int> existSet; unordered_set<int> visitedSet; int maxLength = 0; for(int i = 0; i < nums.size(); i++) existSet.insert(nums[i]); for(int i = 0; i < nums.size(); i++) { int length = 0; if(visitedSet.count(nums[i])) { continue; } else { visitedSet.insert(nums[i]); length++; int left = nums[i]; int right = nums[i]; while(existSet.count(--left)) { visitedSet.insert(left); length++; } while(existSet.count(++right))//<必须使用?前++ { visitedSet.insert(right); length++; } maxLength = max(maxLength,length); } } return maxLength; } };
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
连续数组求最小的miss的数据,还是利用前面介绍的方法,还是利用两个不同的set,其中一个表示已经访问过了的情况,只观察比当前大的数据,
如果已经访问过了就不访问了
class Solution { public: int firstMissingPositive(vector<int>& nums) { if(nums.empty()) { return 1; } int missVal = INT_MAX; int minVal = 1; unordered_set<int> numSet; unordered_set<int> visitedSet; for_each(nums.begin(),nums.end(),[&numSet](int x) { if(x >= 0) numSet.insert(x); }); for(int i = 0; i < nums.size(); i++) { if(nums[i] < 0 || visitedSet.count(nums[i])) { continue; } int right = nums[i]; while(numSet.count(++right)) { visitedSet.insert(right); } missVal = min(missVal,right); } if(numSet.count(1)) return missVal; else { return 1; } } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
Longest Consecutive Sequence 数组连续数字的情况
标签:longest consecutive set map
原文地址:http://blog.csdn.net/xietingcandice/article/details/48109333