一、设计LRU缓存结构
设计LRU(最近最少使用)缓存结构,该结构在构造时确定大小,假设大小为K,并有如下两个功能
1. set(key, value):将记录(key, value)插入该结构
2. get(key):返回key对应的value值
进阶:你是否可以在O(1)的时间复杂度完成set和get操作
class Solution {
public:
/**
* lru design
* @param operators int整型vector<vector<>> the ops
* @param k int整型 the k
* @return int整型vector
*/
private:
int _capacity;
list<pair<int,int>> _lt;
unordered_map<int,list<pair<int,int>>::iterator> _hash;
public:
int get(int key)
{
auto hash_it=_hash.find(key);
if(hash_it!=_hash.end())
{
auto lt_it=hash_it->second;
int value=lt_it->second;
_lt.erase(lt_it);
_lt.push_front(make_pair(key,value));
_hash[key]=_lt.begin();
return value;
}
else
{
return -1;
}
}
void set(int key,int value)
{
auto hash_it=_hash.find(key);
if(hash_it==_hash.end())
{
if(_lt.size()==_capacity)
{
_hash.erase(_lt.back().first);
_lt.pop_back();
}
_lt.push_front(make_pair(key,value));
_hash[key]=_lt.begin();
}
else
{
_lt.erase(hash_it->second);
_lt.push_front(make_pair(key,value));
_hash[key]=_lt.begin();
}
}
vector<int> LRU(vector<vector<int> >& operators, int k) {
// write code here
vector<int> ret;
if(operators.size()==0)
{
return ret;
}
_capacity=k;
for(auto&e:operators)
{
if(e[0]==1)
{
set(e[1],e[2]);
}
else
{
ret.push_back(get(e[1]));
}
}
return ret;
}
};
二、 合并两个有序的数组
描述
给出一个整数数组 和有序的整数数组 ,请将数组 合并到数组 中,变成一个有序的升序数组
注意:
1.可以假设 数组有足够的空间存放
数组的元素,
和
中初始的元素数目分别为
和
,
的数组空间大小为
+
2.不要返回合并的数组,返回是空的,将数组 的数据合并到里面就好了
3.数组在[0,m-1]的范围也是有序的
例1:
A: [4,5,6,0,0,0],m=3
B: [1,2,3],n=3
合并过后A为:
A: [1,2,3,4,5,6]
示例1
输入:
[4,5,6],[1,2,3]
返回值:
[1,2,3,4,5,6]
说明:
A数组为[4,5,6],B数组为[1,2,3],后台程序会预先将A扩容为[4,5,6,0,0,0],B还是为[1,2,3],m=3,n=3,传入到函数merge里面,然后请同学完成merge函数,将B的数据合并A里面,最后后台程序输出A数组
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int end=m+n-1,i=m-1,j=n-1;
while(end>0&&j>=0&&i>=0)
{
if(A[i]>B[j])
A[end--]=A[i--];
else
A[end--]=B[j--];
}
while(j>=0)
{
A[end--]=B[j--];
}
}
};