63.视频推荐的算法|Marscode AI刷题

64 阅读3分钟

1.题目

问题描述

西瓜视频正在开发一个新功能,旨在将访问量达到80百分位数以上的视频展示在首页的推荐列表中。实现一个程序,计算给定数据中的80百分位数。

例如:假设有一个包含从1到100的整数数组,80百分位数的值为80,因为按升序排列后,第80%位置的数字就是80。

99 百分位数:假如有 N 个数据,将数据从小到大排列,99 百分位数是第 N99%位置处的数据(遇到小数时四舍五入获取整数)。一般计算逻辑是先排序,定位到 N99%的位置。返回该位置处的数据。同理,80 百分位数就是第 N*80%位置处的数据。


测试样例

样例1:

输入:data = "10,1,9,2,8,3,7,4,6,5"

输出:8

样例2:

输入:data = "1,0,8,7,3,9,12,6,4,15,17,2,14,5,10,11,19,13,16,18"

输出:15

样例3:

输入:data = "5,3,9,1,7"

输出:7

2.思路

求80百分位数

1.将字符串转为整数数组

2.将数组从小到大排序

3.计算80百分位数的下标

4.求出80百分位数

3.代码

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <cmath>
#include <algorithm>
using namespace std;

int solution(std::string data) {
    // Please write your code here
    // 1.将字符串转为整数数组
    stringstream ss(data);
    string temp;
    vector<int> data_vector;
    // 使用 getline 逐个读取以逗号分隔的部分
    while (getline(ss, temp, ',')) {
        data_vector.push_back(stoi(temp));
    }
    // 2.将数组从小到大排序
    sort(data_vector.begin(), data_vector.end());
    // 3.计算80百分位数的下标
    double index_80 = round(data_vector.size() * 0.8) - 1;
    // 4.求出80百分位数
    return data_vector[index_80];
}

int main() {
    //  You can add more test cases here
    std::cout << (solution("10,1,9,2,8,3,7,4,6,5") == 8) << std::endl;
    std::cout << (solution("1,0,8,7,3,9,12,6,4,15,17,2,14,5,10,11,19,13,16,18") == 15) << std::endl;
    std::cout << (solution("76,100,5,99,16,45,18,3,81,65,102,98,36,4,2,7,22,66,112,97,68,82,37,90,61,73,107,104,79,14,52,83,27,35,93,21,118,120,33,6,19,85,49,44,69,53,67,110,47,91,17,55,80,78,119,15,11,70,103,32,9,40,114,26,25,87,74,1,30,54,38,50,8,34,28,20,24,105,106,31,92,59,116,42,111,57,95,115,96,108,10,89,23,62,29,109,56,58,63,41,77,84,64,75,72,117,101,60,48,94,46,39,43,88,12,113,13,51,86,71") == 96) << std::endl;
    return 0;
}