问题描述
假如西瓜视频即将开发一个功能,将访问量 80 百分位数的视频显示在首页的推荐列表中,请你用程序来实现,获取访问量 80 百分位数。
99 百分位数:假如有 N 个数据,将数据从小到大排列,99 百分位数是第 N99%位置处的数据(遇到小数时四舍五入获取整数)。一般计算逻辑是先排序,定位到 N99%的位置。返回该位置处的数据。同理,80 百分位数就是第 N*80%位置处的数据。
例子:
- 给定数组 1 ~ 100,共 100 个数 ,返回 80 百分位数为 80
输入格式
以逗号分割的数组:10,1,9,2,8,3,7,4,6,5
输出格式
数组中 80 百分位数 —— 8
输入样例
1,0,8,7,3,9,12,6,4,15,17,2,14,5,10,11,19,13,16,18
输出样例
15
数据范围
数组长度 5 <= list.length <= 6000
数组中数据大小 0 <= int[i] <= 600000
分析
排序数组:首先将给定的访问量数组从小到大排序。
计算位置:计算第 N * 80% 位置的索引。
获取数据:根据计算出的索引,获取对应的访问量数据。
#include <iostream>
#include <string>
#include <vector>
#include<sstream>
#include <algorithm> // 用于排序
// 获取访问量 80 百分位数的函数
int get80Percentile(const std::vector<int>& visits) {
if (visits.empty()) {
return 0; // 处理空数组的情况
}
// 复制访问量数组并排序
std::vector<int> sortedVisits = visits;
std::sort(sortedVisits.begin(), sortedVisits.end());
// 计算 80 百分位数的位置
int N = sortedVisits.size();
int position = static_cast<int>(N * 0.8 + 0.5); // 四舍五入
// 确保位置在合法范围内
if (position == 0) {
position = 1;
}
if (position > N) {
position = N;
}
// 位置从 1 开始,所以需要减 1
return sortedVisits[position - 1];
}
int solution(std::string data) {
// Please write your code here
std::vector<int> intArray; // 使用vector来动态存储整数
std::stringstream ss(data); // 创建字符串流
std::string temp;
// 使用getline来逐个读取字符串
while (std::getline(ss, temp, ',')) {
// 将字符串转换为整数并添加到数组中
intArray.push_back(std::stoi(temp));
}
return get80Percentile(intArray);
return -2;
}
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;
}