题目链接:leetcode.
/*
44 / 46 个通过测试用例
超出时间限制
*/
class TimeMap {
unordered_map<string, unordered_map<string, vector<int>>> M;
public:
/** Initialize your data structure here. */
TimeMap() {
}
void set(string key, string value, int timestamp) {
M[key][value].push_back(timestamp);
}
string get(string key, int timestamp) {
string ans = "";
int maxx = 0;
for(auto x : M[key])
{
for(auto i : x.second)
{
if(i > timestamp)
break;
if(i > maxx)
{
maxx = i;
ans = x.first;
}
}
}
return ans;
}
};
/**
* Your TimeMap object will be instantiated and called as such:
* TimeMap* obj = new TimeMap();
* obj->set(key,value,timestamp);
* string param_2 = obj->get(key,timestamp);
*/
查找的时候用二分是最好啦
用一个pair
数组来存储value
和timestamp
,因为set
时时间戳递增,所以pair
数组也是有序递增
内置函数upper_bound( begin,end,num)
,从数组的begin
位置到end-1
位置二分查找第一个大于num
的数字,找到返回该数字的地址,不存在则返回end
。通过返回的地址减去起始地址begin
,得到找到数字在数组中的下标。
/*
执行用时:336 ms, 在所有 C++ 提交中击败了95.48%的用户
内存消耗:125 MB, 在所有 C++ 提交中击败了90.96%的用户
*/
class TimeMap {
unordered_map<string, vector<pair<int, string>>> M;
public:
/** Initialize your data structure here. */
TimeMap() {
}
void set(string key, string value, int timestamp) {
M[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
// 使用一个大于所有 value 的字符串,以确保在 pairs 中含有 timestamp 的情况下也返回大于 timestamp 的位置
pair<int, string> num = {timestamp, string({127})};
auto i = upper_bound(M[key].begin(), M[key].end(), num);
if(i == M[key].begin())
{
return "";
}
else
{
return (i - 1) -> second;
}
}
};
这里不太清楚
ASCII码不超过127,它应该用的是列表初始化