LeetCode 1656. 哈希表
原题链接
简单
作者:
春春打飞舞
,
2022-08-16 01:14:31
,
所有人可见
,
阅读 177
哈希表
直接在类里边定义一个 p 表示插入后的 ptr 的位置,n 表示 id 的最大值
再开一个哈希表,用来存储每一个 id 对应的 value
C++ 代码
class OrderedStream {
public:
int p, n;
unordered_map<int, string> h;
OrderedStream(int n) {
p = 1;
this->n = n;
}
vector<string> insert(int id, string val) {
h[id] = val;
vector<string> res;
if (id != p) return res; // 如果插入的 id 和 当前 ptr 不相等,直接返回空数组
for (int i = id; i <= n; i ++ ) // 否则从当前 id 往后遍历
if (h.count(i)) // 能在哈希表找到的 i 就放进数组
res.push_back(h[i]);
else { // 一旦没找到,说明最长连续序列找完了,那就把 ptr 更新到这个位置上
p = i;
break;
}
return res;
}
};
/**
* Your OrderedStream object will be instantiated and called as such:
* OrderedStream* obj = new OrderedStream(n);
* vector<string> param_1 = obj->insert(idKey,value);
*/