Advertisement
Gistrec

Yandex interview [1]

Mar 4th, 2020
8,070
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <unordered_map>
  2. #include <optional>
  3. #include <iostream>
  4. #include <vector>
  5.  
  6. using SegmentT = std::pair<size_t, size_t>;
  7. using AnswerT  = std::optional<SegmentT>;
  8.  
  9. // Найти непрерывный отрезок массива с заданной суммой
  10. AnswerT getSegment(const std::vector<int> & input, int value) {
  11.     // Получаем массив частных сумм
  12.     std::vector<int> prepare;
  13.  
  14.     size_t sum = 0U;
  15.  
  16.     for (auto elem : input) {
  17.         sum += elem;
  18.         prepare.push_back(sum);
  19.     }
  20.  
  21.     // @first  - частная сумма
  22.     // @second - позиция элемента
  23.     std::unordered_map<int, size_t> pos;
  24.  
  25.     for (size_t index = 0U; index < prepare.size(); index++) {
  26.         // Важно перезаписать!
  27.         pos[prepare[index]] = index;
  28.     }
  29.  
  30.     for (size_t index = 0U; index < input.size(); index++) {
  31.         auto it = pos.find(value - input[index]);
  32.         if (it == pos.end()) continue;
  33.  
  34.         if (it->second < index) {
  35.             return {{ it->second + 1, index }};
  36.         }
  37.     }
  38.     return std::nullopt;
  39. }
  40.  
  41. int main() {
  42.     std::vector<int> input = {1, 2, 3, 5, -3, 5};
  43.     int value = 8;
  44.  
  45.     auto result = getSegment(input, value);
  46.  
  47.     if (result) {
  48.         for (size_t index = result->first; index <= result->second; index++) {
  49.             std::cout << input[index] << " ";
  50.         }
  51.     }else {
  52.         std::cout << "Не найдено" << std::endl;
  53.     }
  54.  
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement