Gistrec icon

Yandex interview [1]

Gistrec | PRO | 03/04/20 07:40:40 AM UTC | 0 ⭐ | 8566 👁️ | Never ⏰ | []
C++ |

1.36 KB

|

None

|

0 👍

/

0 👎

#include <unordered_map>
#include <optional>
#include <iostream>
#include <vector>
 
using SegmentT = std::pair<size_t, size_t>;
using AnswerT  = std::optional<SegmentT>;
 
// Найти непрерывный отрезок массива с заданной суммой
AnswerT getSegment(const std::vector<int> & input, int value) {
    // Получаем массив частных сумм
    std::vector<int> prepare;
 
    size_t sum = 0U;
 
    for (auto elem : input) {
        sum += elem;
        prepare.push_back(sum);
    }
 
    // @first  - частная сумма
    // @second - позиция элемента
    std::unordered_map<int, size_t> pos;
 
    for (size_t index = 0U; index < prepare.size(); index++) {
        // Важно перезаписать!
        pos[prepare[index]] = index;
    }
 
    for (size_t index = 0U; index < input.size(); index++) {
        auto it = pos.find(value - input[index]);
        if (it == pos.end()) continue;
 
        if (it->second < index) {
            return {{ it->second + 1, index }};
        }
    }
    return std::nullopt;
}
 
int main() {
    std::vector<int> input = {1, 2, 3, 5, -3, 5};
    int value = 8;
 
    auto result = getSegment(input, value);
 
    if (result) {
        for (size_t index = result->first; index <= result->second; index++) {
            std::cout << input[index] << " ";
        }
    }else {
        std::cout << "Не найдено" << std::endl;
    }
 
    return 0;
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎