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 element sequence is [1, 2, 3, 4]
. Return its length: 4
.
Example:
Input: arr[]={100,4,200,1,3,2}
Output: 4
Approach
C++
#include <bits/stdc++.h>using namespace std;//funtion to find the longest consecutive//sequenceint longestConsecutive(vector<int> &nums){//sort the arraysort(nums.begin(), nums.end());// if the array is empty then return 0if (nums.size() == 0)return 0;int cnt = 1, res = 1;for (int i = 1; i < nums.size(); i++){//if current element is 1 more then the previous//one then increment the countif (nums[i] == 1 + nums[i - 1]){cnt++;}//if current element is same as the//previous element then continue to the//next positionelse if (nums[i] == nums[i - 1])continue;//else updateelse{//update the resultres = max(res, cnt);cnt = 1;}}//update the resultres = max(res, cnt);return res;}int main(){vector<int> arr = {100, 4, 200, 1, 3, 2};cout << longestConsecutive(arr);return 0;}
No comments:
Post a Comment