Last active
May 11, 2019 11:57
-
-
Save LostInKadath/31e10311af4c24cba3961dc9d6b95ffe to your computer and use it in GitHub Desktop.
Найти минимальный общий элемент трех массивов
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
int Task169(const std::vector<int>& first, | |
const std::vector<int>& second, | |
const std::vector<int>& third) | |
{ | |
// Защита от дурака | |
auto checkSorted = [](const std::vector<int> & v, const std::string& name) | |
{ | |
if (!std::is_sorted(v.begin(), v.end())) | |
throw std::invalid_argument(name + " is not sorted"); | |
}; | |
try | |
{ | |
checkSorted(first, "first"); | |
checkSorted(second, "second"); | |
checkSorted(third, "third"); | |
} | |
catch (const std::invalid_argument& e) | |
{ | |
// Один из массивов не отсортирован | |
std::cout << e.what() << '\n'; | |
return (std::numeric_limits<int>::min)(); | |
} | |
// Вспомогательная функция вычисления максимума трех чисел | |
auto max3 = [](int a, int b, int c) | |
{ | |
const int m = a > b ? a : b; | |
return m > c ? m : c; | |
}; | |
auto firstIt = first.begin(); | |
auto secondIt = second.begin(); | |
auto thirdIt = third.begin(); | |
while (firstIt != first.end() | |
&& secondIt != second.end() | |
&& thirdIt != third.end()) | |
{ | |
// Элемент найден | |
if (*firstIt == *secondIt && *secondIt == *thirdIt) | |
return *firstIt; | |
const auto maxElement = max3(*firstIt, *secondIt, *thirdIt); | |
// Подтягиваем "запоздавшие" итераторы к максимальному на данный момент элементу | |
if (*firstIt < maxElement) | |
++firstIt; | |
if (*secondIt < maxElement) | |
++secondIt; | |
if (*thirdIt < maxElement) | |
++thirdIt; | |
} | |
// Элемент не найден | |
return (std::numeric_limits<int>::min)(); | |
} | |
int main() | |
{ | |
std::cout << Task169( | |
{ 1, 5, 10, 11, 90 }, | |
{ -10, -9, -8, -7, -6, -5, 5, 7, 8, 40 }, | |
{ 0, 5, 6, 12, 20, 30 } | |
) << '\n'; | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment