华为机试:查找接口成功率最优时间段

题目来源

  • 华为机试:查找接口成功率最优时间段

题目描述

华为机试:查找接口成功率最优时间段_第1张图片
华为机试:查找接口成功率最优时间段_第2张图片

题目解析

#include

using namespace std;

int getSum(std::vector<int> &vec, int start, int end){
    int sum = 0;
    for (int i = start; i <= end; ++i) {
        sum += vec[i];
    }
    return sum;
}

std::string process(std::vector<int> &vec, int minAverageLost){
    int maxLen = 0;
    std::vector<std::string> ans;
    for (int start = 0; start < vec.size() - 1; ++start) {
        for (int end = start + 1; end < vec.size(); ++end) {
            int sum = getSum(vec, start, end);
            int currLen = end - start + 1;
            std::string tmp;
            if(sum == 0 && minAverageLost >= 0){
                tmp = std::to_string(start) + "-" + to_string(end);
            }else{
                if(sum <= minAverageLost * currLen){
                    tmp = std::to_string(start) + "-" + to_string(end);
                }
            }

            if(!tmp.empty()){
                if(maxLen == currLen){
                    ans.emplace_back(tmp);
                }else if(currLen > maxLen){
                    ans.clear();
                    ans.push_back(tmp);
                    maxLen = currLen;
                }
            }
        }
    }


    if(ans.empty()){
        return "NULL";
    }

    std::string str;
    for (const auto & an : ans) {
        str = str.empty() ? an : str + " " + an;
    }
    return str;
}
int main(int argc, char **argv)
{
    std::vector<int> vec = {0, 0, 100, 2, 2, 99, 0, 2};
    int minAverageLost = 2;
    std::cout << process(vec, minAverageLost);
}

你可能感兴趣的:(算法与数据结构,华为)