Consecutive numbers in the Longest Consecutive Sequence Array
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.
Find the maximum length of the continuous array. Use two set arrays and one array to store the accessed array. If the accessed array has been accessed, it does not need to be accessed again.
Class Solution {public: int longestConsecutive (vector
& Nums) {if (nums. empty () {return 0;} unordered_set
ExistSet; unordered_set
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) // <required? 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.
To find the smallest miss data in a continuous array, use the method described above or use two different sets. One of them indicates that the accessed data has been accessed, and only observes the data larger than the current one,
If you have already accessed it, you will not be able to access it.
class Solution {public: int firstMissingPositive(vector
& nums) { if(nums.empty()) { return 1; } int missVal = INT_MAX; int minVal = 1; unordered_set
numSet; unordered_set
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; } }};