https://leetcode-cn.com/problems/rank-from-stream-lcci/
假设你正在读取一串整数。每隔一段时间,你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。请实现数据结构和算法来支持这些操作,也就是说:
实现 track(int x) 方法,每读入一个数字都会调用该方法;
实现 getRankOfNumber(int x) 方法,返回小于或等于 x 的值的个数。
思路:数据量很小只有2000,直接插入到数组后面,在查询时排序,然后对有序序列二分。
使无序后缀子序列有序后再整体排序能快一点。。。
class StreamRank {
public:
int arr[2001];
int cnt;
int pre;
StreamRank() {
cnt = 0;
pre = 0;
}
void track(int x) {
arr[cnt++] = x;
}
int getRankOfNumber(int x) {
sort(arr+pre, arr+cnt);
sort(arr, arr+cnt);
int* ans = upper_bound(arr, arr+cnt, x);
pre = cnt;
return ans - arr;
}
};