Longest consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
for example,
given [100, 4, 1, 3, 2] ,
the longest consecutive elements sequence Is [1, 2, 3, 4] . Return its length: 4 .
Looking for the length of the largest contiguous array, using two set arrays, an array that stores the array that has been accessed, and if it has already been accessed, it is no longer required to be accessed.
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))//< must be used, front + + {Visitedset.insert (right) ; length++; } maxLength = max (maxlength,length); }} return maxLength; }};
First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]Return3,
and[3,4,-1,1]Return2.
A continuous array of the smallest miss data, or using the method described earlier, or using two different sets, one of which represents a situation that has been visited, only to observe larger than the current data,
If you've already visited it, you don't have access to the
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;}} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Longest consecutive Sequence array continuous number case