Leetcode 981:基于时间的键值存储

创建一个基于时间的键值存储类TimaMap,它支持下面两个操作:

1、set(string key,string value,int timestamp)

  • 存储键key、值value,以及给定的时间戳timestamp

2、get(string key,int timestamp)

  • 返回先前调用set(key,value,timestamp)所存储的值,其中timestamp_prev <= timestamp
  • 如果有多个这样的值,则返回对应的最大的timestamp的那个值
  • 如果没有值,则返回空字符串(" ")。

示例1:

输入:inputs = ["TimeMap","set","get","get","set","get","get"],inputs=[[],["foo","bar","1"],["foo","1"],["foo","3"],["foo","bar2","4"],["foo","4"],["foo","5"]]

输出:[null,null,"bar","bar",null,"bar2","bar2"]

解题思路

首先本题要存放键值对,首先想到要使用map,其次对于一个key可以存放多个不同的value和时间戳,所以需要建立一个包含string和int型变量的结构node,然后建立<string,vector<node>>型map

struct node{
	string value;
	int timestamp;
	node(string _value,int _tmp):value(_value),timestamp(_tmp){}
	friend bool operator<(node a,node b){
		return a.timestamp < b.timestamp;
	}
};
class TimeMap {
public:
    /** Initialize your data structure here. */
    TimeMap() {
        
    }
    
    void set(string key, string value, int timestamp) {
        map<string,vector<node> >::iterator it;
			it = mp.find(key);
			if(it != mp.end()){
				mp[key].push_back(node(value,timestamp));
			}else{
				vector<node> vect;
				vect.push_back(node(value,timestamp));
				mp[key] = vect;
			}
    }
    
    string get(string key, int timestamp) {
        map<string,vector<node> >::iterator it;
			it = mp.find(key);
			if(it != mp.end() && it->second[0].timestamp <= timestamp){
				vector<node>::iterator itt;
				itt = lower_bound(it->second.begin(),it->second.end(),node(" ",timestamp));
				if(itt != it->second.end()){
					if(itt->timestamp == timestamp) return itt->value;
					itt--;
					return itt->value;
				}
				return it->second[it->second.size()-1].value;
			}
			return "";
    }
    private:
		map<string,vector<node> > mp;
};

猜你喜欢

转载自blog.csdn.net/weixin_35338624/article/details/87898795
981
今日推荐