fork download
  1.  
  2.  
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. int longestSuccessiveElements(vector<int>&a) {
  8. int n = a.size();
  9. if (n == 0) return 0;
  10.  
  11. int longest = 1;
  12. unordered_set<int> st;
  13. //put all the array elements into set:
  14. for (int i = 0; i < n; i++) {
  15. st.insert(a[i]);
  16. }
  17.  
  18. //Find the longest sequence:
  19. for (auto it : st) {
  20. //if 'it' is a starting number:
  21. if (st.find(it - 1) == st.end()) {
  22. //find consecutive numbers:
  23. int cnt = 1;
  24. int x = it;
  25. while (st.find(x + 1) != st.end()) {
  26. x = x + 1;
  27. cnt = cnt + 1;
  28. }
  29. longest = max(longest, cnt);
  30. }
  31. }
  32. return longest;
  33.  
  34. }
  35.  
  36. int main()
  37. {
  38. vector<int> a = {100, 200, 1, 2, 3, 4};
  39. int ans = longestSuccessiveElements(a);
  40. cout << "The longest consecutive sequence is " << ans << "\n";
  41. return 0;
  42. }
  43.  
  44.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
The longest consecutive sequence is 4