Skip to content

Instantly share code, notes, and snippets.

@sergiosvieira
Created March 31, 2021 14:15
Show Gist options
  • Save sergiosvieira/5ce87c3aad1f8c9cf1142bcfa87f9b6a to your computer and use it in GitHub Desktop.
Save sergiosvieira/5ce87c3aad1f8c9cf1142bcfa87f9b6a to your computer and use it in GitHub Desktop.
Find the longest contiguous sequence of integer in "a" that belongs to vector "b"
#include <iostream>
#include <vector>
#include <algorithm>
using std::cout;
using Vector = std::vector<int>;
std::ostream& operator<<(std::ostream& out, const Vector& v) {
out << "[";
for (size_t i = 0; i < v.size(); ++i) {
out << v[i];
if (i != v.size() - 1) out << ", ";
}
out << "]";
return out;
}
/*
* Find the longest contiguous sequence of integer in "a" that belongs to vector "b"
*/
int main() {
Vector a = {1, 5, 6, 1, 1, 3, 7, 8, 9};
Vector b = {1, 3, 5};
size_t be = 0; size_t en = 0;
Vector r;
for (size_t i = 0; i < a.size(); ++i) {
if (std::find(b.begin(), b.end(), a[i]) == b.end()) {
if (en - be > r.size()) {
r = Vector(en - be, 0);
std::copy(a.begin() + be, a.begin() + en, r.begin());
}
if (i + 1 < a.size()) be = i + 1;
}
en = std::max(i, be) + 1;
}
cout << r << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment