leetcode笔记
82. Remove Duplicates from Sorted List II
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
下面代码是自写hashmap版,练一下hashmap,用一般的map<int,int>红黑树map也能过。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/ class MyHash {
static const int MAX = ;
static const int MOD = ;
static const int WHAT = ;
static const int INVALID = -;
pair<int,int> a[MAX];
bool used[MAX];
int siz =;
int myhash(int key){
if(siz==MOD)return MOD;
int pos = key*WHAT%MOD;
while(pos<)pos=-(pos+);
while(used[pos] && a[pos].first!=key)pos = (pos+)%MOD;
return pos;
}
public:
int insert(pair<int,int> kv){
int pos = myhash(kv.first);
if(pos==MOD)return -;
if(!used[pos]){
used[pos]=true;
siz++;
}
a[pos] = kv;
return ;
}
int get(int key){
int pos = myhash(key);
if(a[pos].first==key)return a[pos].second;
else return INVALID;
} void add(int key, int ad){
int pos = myhash(key);
if(!used[pos]){
insert(make_pair(key,));
}
a[pos].second+=ad;
}
}; class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
MyHash count;
ListNode* cur = head;
while(cur!=NULL){
count.add(cur->val,);
cur=cur->next;
}
ListNode newhead();
newhead.next = head;
cur=&newhead;
while(cur!=NULL){
while(cur->next !=NULL && count.get(cur->next->val)>){
cur->next = cur->next->next;
}
cur = cur->next;
}
return newhead.next;
}
};
106. Construct Binary Tree from Inorder and Postorder Traversal
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
根据中序后序建树。
一般思想:后序里面越靠前面的越是根,找到中序的[st,ed]中最是根的,建个结点,再递归分支左结点、右结点。
进一步思想:每次找最是根的那个要找区间最值,能不能直接找到那个根?根据后序遍历的规律,左子树的点和右子树的点肯定是分开的两部分,左边和右边,其中每部分的最后一个就是那个子树的根节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
map<int,int> mp;
TreeNode* build(vector<int>& inorder, vector<int>& postorder, int inst, int ined , int post, int poed){
if(inst>ined || post>poed)return NULL;
int inmid = mp[postorder[poed]];
TreeNode * ret = new TreeNode(inorder[inmid]);
ret->left = build(inorder, postorder, inst, inmid-, post, post + ((inmid-) - inst));
ret->right = build(inorder, postorder, inmid+, ined,poed - - (ined - (inmid+)),poed - );
return ret;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
for(int i=; i<inorder.size(); i++){
mp[inorder[i]] = i;
}
return build(inorder, postorder, , inorder.size()-, , postorder.size()-);
}
};
130. Surrounded Regions
https://leetcode.com/problems/surrounded-regions/
给一个矩阵,有X有O,把不与边界相连的O fill成X。
宽搜。我深搜有的点RE了,可恶。
宽搜代码:
#include<bits/stdc++.h>
using namespace std;
class Solution {
const int gx[] = {,-,,};
const int gy[] = {,,,-};
int n;
int m;
void fill(vector<vector<char>>&board , int x, int y,char c){
queue<int> qx;
queue<int> qy;
qx.push(x);
qy.push(y);
board[x][y] = c;
while(!qx.empty()){
x = qx.front();
y = qy.front();
qx.pop();
qy.pop();
for(int i=; i<; i++){
int xx = x+gx[i];
int yy = y+gy[i];
if(xx< || xx>=n || yy< || yy>=m)continue;
if(board[xx][yy]=='X'|| board[xx][yy]=='')continue;
board[xx][yy] = c;
qx.push(xx);
qy.push(yy);
}
}
}
public:
void solve(vector<vector<char>>& board) {
if(board.empty())return;
n = board.size();
m = board[].size();
for(int i=; i<n; i++){
for(int j=; j<m; j++){
if((i== || j==|| i==n- || j==m-)&&board[i][j]=='O'){
fill(board, i, j,'');
}
}
}
for(int i=; i<n-; i++){
for(int j=; j<m-; j++){
if(board[i][j]=='O'){
fill(board, i, j,'X');
}
}
}
for(int i=; i<n; i++){
for(int j=; j<m; j++){
if(board[i][j]==''){
board[i][j] = 'O';
}
}
}
}
}; int main(){
vector<vector<char> >board ={{'O','O'},{'O','O'}};
Solution so;
so.solve(board);
return ;
}
137. Single Number II
https://leetcode.com/problems/single-number-ii/
好多数出现3次,只有一个数出现1次。
解法:https://discuss.leetcode.com/topic/22821/an-general-way-to-handle-all-this-sort-of-questions
代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
//00 01 10
//01 10 00
int a = ;
int b = ;
for(int x:nums){
int na = (x & ~a & b) | (~x & a & ~b);
int nb = (x & ~b & ~a)| (~x & ~a & b);
a = na;
b = nb;
}
return ~a & b;
}
};
138. Copy List with Random Pointer
https://leetcode.com/problems/copy-list-with-random-pointer/
深拷贝带随机指针的链表。
不用额外空间的方法:把A->B->C 各个节点复制一份放在旁边,A->A`->B->B`->C->C`,然后x`->random = x`->random->next。然后再把这个拆成两个链表。
注意原来的链表不能破坏,要把它拆回原样。(我以为能随便乱搞,结果错了好久,可恶)
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head)return head;
RandomListNode *cur = head, *x,*t;
while(cur){
t = cur->next;
x = new RandomListNode(cur->label);
x->next = t;
x->random = cur->random;
cur->next = x;
cur = t;
}
cur = head;
while(cur){
cur = cur->next;
if(cur->random) cur->random = (cur->random)->next;
cur= cur->next;
}
x = head->next;
cur = head;
while(cur){
t = cur->next;
cur->next = cur->next->next;
if(cur->next)t->next = cur->next->next;
else t->next = NULL;
cur = cur->next;
}
return x;
}
};
146. LRU Cache
https://leetcode.com/problems/lru-cache/
LRU。每次满的时候把最久没用的那个踢出去。
单链表+map,查找O(logn) 冲突O(n),因为要扫到最后一个。如果要冲突O(1)的话要双链表。
https://leetcode.com/problems/lru-cache/
双向链表,把插入和删除函数抽了出来,好像不错:
struct kvNode{
int key;
int val;
kvNode *left, *right;
kvNode(int k,int v):key(k), val(v),left(NULL), right(NULL){};
kvNode():key(),val(),left(NULL),right(NULL){};
};
class LRUCache{
int cnt = ;
int ma;
kvNode h,tail;
map<int,kvNode*> mp;
void insert(kvNode* f, kvNode* now){;
now->left = f;
now->right = f->right;
f->right->left = now;
f->right = now;
}
void del(kvNode* now){
now->left->right = now->right;
now->right->left = now->left;
}
public:
LRUCache(int capacity) {
ma = capacity;
h.right=&tail;
tail.left = &h;
mp.clear();
} int get(int key) {
if(mp.find(key)!=mp.end()){
kvNode *p = mp[key];
del(p);
insert(&h, p);
return p->val;
}
return -;
} void set(int key, int value) {
if(ma==)return;
if(mp.find(key)==mp.end()){
if(cnt==ma){
kvNode *q = tail.left;
mp.erase(q->key);
del(q);
delete q;
cnt--;
}
kvNode *p = new kvNode(key,value);
insert(&h,p);
mp[key] = p;
cnt++;
}else{
kvNode *p = mp[key];
p->val = value;
del(p);
insert(&h, p);
}
}
};
148. Sort List
https://leetcode.com/problems/sort-list/
链表排序。
当然是用归并排序啦!都不用开多少新的空间。
不过第一次写的时候,居然写错,可恶,有点难。
关键在于,比如把AB分为A和B两份,我们要先存A之前的那个点aa、B之后的那个点bb,排完以后要他们连起来, aa->排完的->bb。
为了更方便排,先要把他们切开,写一个split(node, length)函数,把node开始的length个结点之后变成null,把结尾之后的那个点返回。
这样,就很容易排了!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* merge(ListNode* l, ListNode *r){
ListNode temp();
ListNode *cur = &temp;
while(l && r){
if(l->val < r->val){
cur->next = l;
cur = l;
l = l->next;
}else{
cur->next = r;
cur = r;
r=r->next;
}
}
if(l){
cur->next = l;
}else cur->next = r;
cur = temp.next;
return cur;
} ListNode *split(ListNode *st, int w){
for(int i=;st&& i<w; i++)st = st->next;
if(st==NULL)return NULL;
ListNode *p = st->next;
st->next = NULL;
return p;
}
public:
ListNode* sortList(ListNode* head) {
ListNode temp();
ListNode *hh = &temp;
hh->next = head;
int siz=;
ListNode *cur = head;
while(cur){
siz++;
cur=cur->next;
}
for(int w=; w<=siz; w*=){
ListNode *tail = hh, *mid,*r;
while(tail->next){
mid = split(tail->next,w);
r = split(mid,w);
tail->next = merge(tail->next, mid);
for(int i=;(tail->next)&& i<*w; i++){
tail = tail->next;
}
tail->next = r;
}
}
return hh->next;
}
};
168. Excel Sheet Column Title
171. Excel Sheet Column Number
https://leetcode.com/problems/excel-sheet-column-title/
https://leetcode.com/problems/excel-sheet-column-number/
168是列数转excel列号,1对应A,27对应AA。
171是反过来转,excel列号转列数。
解:因为这个和进制有一点差别,没法直接把字母当做26进制,只好认真观察,瞪眼法。
观察草稿:
A Z
AA = +
AZ = +
BA = * +
ZA * +
ZZ * +
AAA * + +
AZZ * + * + AA AZ -> A Z (X-)%
AA AZ -> A (X-) /
AAA AZZ -> AA AZ
168代码:
class Solution {
public:
string convertToTitle(int n) {
string ret = "";
while(n){
int x = (n-)%;
char c = 'A'+x;
ret = c+ret;
n = (n-)/;
}
return ret;
}
};
171代码:
class Solution {
public:
int titleToNumber(string s) {
int ans=;
int bei=;
for(int i = s.size()-; i>=; i--){
int x = s[i]-'A' + ;
ans += bei*x;
bei*=;
}
return ans;
}
};
209. Minimum Size Subarray Sum
https://leetcode.com/problems/minimum-size-subarray-sum/
在数列中找 和大于等于s的连续子串 的最小长度。
1.求和不能每次都直接一个个加(O(n)),可以像我这样弄一个求和数组求(O(1)),或者在滑动窗口的时候维护(可能比较麻烦,求和数组比较直接)。
2.注意题目要求,如果没有满足需求的就返回0,包括数组为空的情况。
3.一顿滑动
4.补充:题目说做了O(n)的还要试试O(nlogn)的……what?看了别人的答案,O(n)的一般是滑动窗口不用求和数组,这样空间O(1)。O(nlogn)的是二分+求和数组的。
O(n):
class Solution {
public:
vector<int> a;
int sum(int st, int ed){
return a[ed+] - a[st];
} int minSubArrayLen(int s, vector<int>& nums) {
int siz = nums.size();
while(!a.empty())a.pop_back();
a.push_back();
for(int i=; i<siz; i++)
a.push_back(a[i] + nums[i]);
int r=,l=;
while(sum(l,r)<s && r<siz)r++;
if(r>=siz)return ;
int ans = r-l+;
for(;r<siz;r++){
while(r>l && sum(l+,r)>=s)l++;
ans = min(r-l+, ans);
}
return ans;
}
};
O(nlogn):
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> a;
int sum(int st, int ed) {
return a[ed+] - a[st];
} int bs(int st,int ed, int s){
int l=st, r=ed;
int re = INT_MAX;
while(l<=r){
int mid = l + (r-l)/;
if(sum(st,mid)>=s)
r=mid-;
else l=mid+;
}
if(l<=ed)re=l;
return re;
} int minSubArrayLen(int s, vector<int>& nums) {
int siz = nums.size();
while(!a.empty())a.pop_back();
a.push_back();
for(int i=; i<siz; i++)
a.push_back(a[i] + nums[i]);
int ans = INT_MAX;
for(int st=; st<siz; st++){
int x = bs(st,siz-,s);
if(x!=INT_MAX)
ans = min(ans,x - st + );
}
return ans!=INT_MAX?ans:;
}
}; int main(){
int s=;
int arr[]={,,,,,};
vector<int> v(arr,arr+);
Solution so;
int ans = so.minSubArrayLen(s,v);
printf("%d\n",ans);
return ;
}
211. Add and Search Word - Data structure design
https://leetcode.com/problems/add-and-search-word-data-structure-design/
做一个数据结构,支持插入字符串和判断字符串是否在,判断时支持用点.代替任意字母,其他的只能是a到z小写字母。
解:用字典树,遇到点的时候用26种递归去找。
class TrieNode{
public:
bool isKey;
TrieNode* child[];
TrieNode():isKey(false){
memset(child,NULL, sizeof(child));
}
}; class WordDictionary {
TrieNode root;
bool find(const char *s, TrieNode *cur){
int j=;
while(s[j]){
char c = s[j];
if(c!='.'){
int q = c - 'a';
if(cur->child[q]) cur = cur->child[q];
else return false;
}else{
for(int i=; i<; i++){
if(cur->child[i]){
if(find(s+j+, cur->child[i])) return true;
}
}
return false;
}
j++;
}
if(cur->isKey)return true;
else return false;
}
public: // Adds a word into the data structure.
void addWord(string word) {
TrieNode* cur = &root;
for(char c:word){
int q = c - 'a';
if(cur->child[q] == NULL){
cur ->child[q] = new TrieNode();
}
cur = cur->child[q];
}
cur->isKey = true;
} // Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word) {
return find(word.c_str(), &root);
}
}; // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
227. Basic Calculator II
https://leetcode.com/problems/basic-calculator-ii/
表达式求值,加减乘除,不带括号。
可恶,看了题解,发现这个不带括号的直接瞎比做就行了,我还想什么栈方法什么递归方法想了半天,简直逗,题解都是只要十几行的。
下面是没看题解写的。
=============分割线============
随机到这题发现我真的弱,这是基础题啊,我都不记得怎么做,需要认真复习了。
方法两种:
1.先用一个符号栈中缀转后缀,再用一个操作数栈进行后缀表达式求值。
2.用两个栈,一个符号栈一个操作数栈,直接对中缀表达式求值。
中缀转后缀的代码:
class Solution {
map<char,int> priority;
int cal(vector<int> v){
stack<int> s;
for(int x:v){
if(x>=)s.push(x);
else{
char c = -x;
int z = s.top();
s.pop();
int y = s.top();
s.pop();
int w;
switch(c){
case '+':
w = y+z;
break;
case '-':
w=y-z;
break;
case '*':
w=y*z;
break;
case '/':
w=y/z;
break;
}
s.push(w);
}
}
return s.top();
} vector<int> mid2back(vector<int> v){
vector<int> ret;
stack<char> s;
for(int x:v){
if(x>=)ret.push_back(x);
else{
char c = -x;
while(!s.empty() && priority[s.top()]>=priority[c]){
ret.push_back(-s.top());
s.pop();
}
s.push(c);
}
}
while(!s.empty()){
ret.push_back(-s.top());
s.pop();
}
return ret;
} vector<int> str2vec(string s){
vector<int> ret;
int num=;
for(char c:s){
if(c==' ')continue;
if(c>='' && c<='') num = num* + (c - '');
else {
ret.push_back(num);
num=;
char ch = c;
ret.push_back(-c);
}
}
ret.push_back(num);
return ret;
} public:
Solution(){
priority['*']=;
priority['/']=;
priority['+']=;
priority['-']=;
} int calculate(string s) {
vector<int> midexp = str2vec(s);
vector<int> backexp = mid2back(midexp);
int ans = cal(backexp);
return ans;
}
};
思考:如果带括号怎么做?中缀转后缀的时候就要将括号消掉了,遇到右括号就要疯狂出栈直到消掉左括号。难道是左右括号优先级1,加减2,乘除3?特殊处理弹出左括号的时候就结束while,并且右括号不入栈,好像不错。不对,这样入左括号的时候,之前的就要弹光了,难道左括号特殊处理不管优先级就进站?好像可以。
312. Burst Balloons
https://leetcode.com/problems/burst-balloons/
有一排乘法恐狼先锋,你杀一个i号狼会收到a[i-1]*a[i]*a[i+1]的伤害,然后剩下的会连起来。求能受到的最大伤害。
和hdu 5115 Dire Wolf 题解 (ACM/ICPC 14 北京站 现场赛) 差不多。别人的题解:http://blog.163.com/infog@126/blog/static/783768072014114714157/
区间DP代码:
class Solution {
public:
int maxCoins(vector<int>& nums) {
int f[nums.size()+][nums.size()+];
memset(f,,sizeof(f));
int n=nums.size();
for(int k=; k<n; k++){
for(int i=; i+k<n; i++){
int t=;
if(i->=)t*=nums[i-];
if(i+k+<n)t*=nums[i+k+];
for(int j=i; j<=i+k; j++){
f[i][i+k] = max(f[i][i+k], f[i][j-] + f[j+][i+k] + t*nums[j]);
}
}
}
return f[][n-];
}
};
352. Data Stream as Disjoint Intervals
https://leetcode.com/problems/data-stream-as-disjoint-intervals/
做一个数据结构,支持插入数字,输出一堆区间。
用一个map记各个数字,指向Interval编号。
插入数字的时候维护区间左右端点, 合并区间的时候删Interval。
注意不仅要维护左右端点,当前插入点也要记一下,不然会重复插入,我这个错找了好久。
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class SummaryRanges {
map<int,int> mp;
map<int,Interval>itv;
int n=;
public:
/** Initialize your data structure here. */
SummaryRanges() {
mp.clear();
itv.clear();
n=;
} void addNum(int val) {
if(mp.find(val)==mp.end()){
int l =val;
int r = val;
if(mp.find(val-)!=mp.end()) l = min(l, itv[mp[val-]].start);
if(mp.find(val+)!=mp.end()) r = max(r, itv[mp[val+]].end);
if(l==r){
itv[n] = Interval(val,val);
mp[val]=n;
n++;
}else if(l!=val && r!=val){
itv.erase(mp[r]);
itv[mp[l]].start = l;
itv[mp[l]].end = r;
mp[r]=mp[l];
mp[val]=mp[l];// use for judge if val insert before
}else{
int x = (l==val)?r:l;
itv[mp[x]].start = l;
itv[mp[x]].end = r;
mp[val] = mp[x];
}
}
} static bool cmp(const Interval &x,const Interval &y){
return x.start < y.start;
} vector<Interval> getIntervals() {
vector<Interval> ret;
for(pair<int,Interval> it:itv){
ret.push_back(it.second);
}
sort(ret.begin(), ret.end(), cmp);
return ret;
}
}; /**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* vector<Interval> param_2 = obj.getIntervals();
*/
374. Guess Number Higher or Lower
https://leetcode.com/problems/guess-number-higher-or-lower/
幸运52猜数字,注意点:1.C++ 爆int,平均数要用x = l + (r-l)/2;
2.当l==r时就不用再猜一次了可以直接return。(不关键)
394. Decode String
https://leetcode.com/problems/decode-string/
递归:
class Solution {
string decode(string s, int &i){
int cnt=;
string ret = "";
for(; s[i]!=']'; i++){
if(s[i]>='' && s[i]<=''){
cnt = cnt * + (s[i]-'');
}else if(s[i]=='['){
i++;
string t = decode(s,i);
for(int j=; j<cnt; j++)
ret += t;
cnt = ;
}else ret += s[i];
}
return ret;
}
public:
string decodeString(string s) {
int i=;
return decode(s+"]", i);
}
};
非递归:
class Solution {
public:
string decodeString(string s) {
int i=;
stack<int> si;
stack<string> ss;
string t="";
int cnt = ;
for(char c:s){
if(c>='' && c<=''){
cnt = cnt * + (c-'');
}else if(c=='['){
si.push(cnt);
cnt=;
ss.push(t);
t="";
}else if(c==']'){
cnt = si.top();
si.pop();
string tt = t;
t = ss.top();
ss.pop();
for(int j=; j<cnt; j++)
t += tt;
cnt = ;
}else t += c;
}
return t;
}
};
450. Delete Node in a BST
https://leetcode.com/problems/delete-node-in-a-bst/
删除二叉搜索树中的一点。又不用平衡,随便搞搞,虽然我搞错了好久……
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int deleteLittle(TreeNode * cur){
TreeNode * fa = cur;
while(cur->left!=NULL){
fa = cur;
cur = cur->left;
}
int ret = cur->val;
fa->left = cur->right;//this, I wrote wrong : fa->left = NULL, ouch! spend much time to find and fix it.
return ret;
}
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root)return NULL;
if(root->val ==key){
if(!root->left)return root->right;
if(!root->right)return root->left;
if((root->right)->left!=NULL){
root->val = deleteLittle(root->right);
}else{
root->val = root->right->val;
root->right = root->right->right;
}
}else{
if(key < root->val){
root->left = deleteNode(root->left, key);
}else
root->right = deleteNode(root->right, key);
}
return root;
}
};
460. LFU Cache
https://leetcode.com/problems/lfu-cache/
LFU,Least Frequently Used (LFU) ,是冲突时先删频率最小的,频率相同的话删最久没用过的。(另外一种叫LRU,就是删最久没用过的)。
做完发现怎么是hard,可恶,不过复习了LRU LFU的概念。
这个关键是,冲突时怎么找到最小的那个。每次冲突都要找最小的,很容易想到需要一个能够支持插入、删除、快速找到最小的这三中操作的数据结构,这不就是,map嘛,底层是红黑树实现,插入删除查找都是Logn,无敌。如果是每次在数组里扫最小的,那是O(n)。
另外用key找value,这个我也用的map,总的时间复杂度大概,查找是logn,插入时冲突,也是logn,好像是这个样子,每次操作logn,m次操作mlogn。
题目提示说要O(1)操作,那key找value可以hash,这个找最小要怎么O(1)?等我想一想。
logn代码:
class LFUCache {
int capa;
int used;
typedef pair<pair<int,int>,pair<int,int> > p4i;// frequency, time, key, value
vector<p4i> v; //v[pos]
map<int,int> mp; //<key, pos>
map<pair<int,int>, int> freqTimePos; // frequency, time , pos
int time;
public:
LFUCache(int capacity) {
capa = capacity;
used=;
time=;
v.clear();
mp.clear();
} int get(int key) {
if(mp.find(key)!=mp.end()){
time++;
int p = mp[key];
freqTimePos.erase(v[p].first);
v[p].first.second = time;
v[p].first.first++;
freqTimePos[v[p].first]=p;
return v[p].second.second;
}else return -;
} void put(int key, int value) {
time++;
if(mp.find(key)!=mp.end()){
int p = mp[key];
freqTimePos.erase(v[p].first);
v[p].first.second = time;
v[p].first.first++;
freqTimePos[v[p].first]=p;
v[p].second.second = value;
}else{
if(used<capa){
used++;
v.push_back(make_pair(make_pair(,time),make_pair(key,value)));
freqTimePos[v.back().first]=v.size()-;
mp[key]=v.size()-;
}else{
if(capa==)return;
int ekey,epos;
map<pair<int,int>, int>::iterator it = freqTimePos.begin();
epos = it->second;
ekey = v[epos].second.first;
mp.erase(ekey);
mp[key]=epos;
freqTimePos.erase(v[epos].first);
v[epos] = make_pair(make_pair(,time),make_pair(key,value));
freqTimePos[v[epos].first]=epos;
}
}
}
}; /**
* Your LFUCache object will be instantiated and called as such:
* LFUCache obj = new LFUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
leetcode笔记的更多相关文章
- Leetcode 笔记 113 - Path Sum II
题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- Leetcode 笔记 110 - Balanced Binary Tree
题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...
- Leetcode 笔记 100 - Same Tree
题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
- Leetcode 笔记 101 - Symmetric Tree
题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...
- Leetcode 笔记 36 - Sudoku Solver
题目链接:Sudoku Solver | LeetCode OJ Write a program to solve a Sudoku puzzle by filling the empty cells ...
- Leetcode 笔记 35 - Valid Soduko
题目链接:Valid Sudoku | LeetCode OJ Determine if a Sudoku is valid, according to: Sudoku Puzzles - The R ...
- Leetcode 笔记 117 - Populating Next Right Pointers in Each Node II
题目链接:Populating Next Right Pointers in Each Node II | LeetCode OJ Follow up for problem "Popula ...
随机推荐
- JAVA NIO Buffer
所谓的输入,输出,就是把数据移除或移入缓冲区. 硬件不能直接访问用户控件(JVM). 基于存储的硬件设备操控的是固定大小的数据块儿,用户请求的是任意大小的或非对齐的数据块儿. 虚拟内存:使用虚 ...
- 基于easyUI实现组织结构树图形
一. 准备工作 1. 点击此下载相关文件 2. 进入 js 文件夹,解压缩 jquery-easyui-1.5.rar 到当前文件夹 二. 在浏览器中运行 organize.html 文件,即可看到效 ...
- 常用linux手头命令
过滤ip ifconfig eth0|grep -oP "([0-9]{1,3}\.){3}[0-9]{1,3}"|sed -n '1p' ifconfig|sed -n '2p' ...
- [LeetCode] Arithmetic Slices II - Subsequence 算数切片之二 - 子序列
A sequence of numbers is called arithmetic if it consists of at least three elements and if the diff ...
- [LeetCode] Valid Phone Numbers 验证电话号码
Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bas ...
- AngularJS的基础元素应用
<!doctype html> <!-- 标记ng-app告诉AngularJS处理整个HTML页并引导应用 --> <html ng-app> <head& ...
- Hello session
1. session 随想 HTTP 的无状态,也就是说,每次请求都是独立的线程.这里所说的无状态其实就是一种隔离的意思.举个例子比如购物车,你先选择A商品,加入购物车,这里就是A线程,然后在选择B商 ...
- 知乎一道前端面试题详解,关于this的使用
请说明要输出正确的myName的值要如何修改程序?并解释原因 foo = function(){ this.myName = "Foo function."; } foo.prot ...
- Beennan的内嵌汇编指导(译)Brennan's Guide to Inline Assembly
注:写在前面,这是一篇翻译文章,本人的英文水平很有限,但内嵌汇编是学习操作系统不可少的知识,本人也常去查看这方面的内容,本文是在做mit的jos实验中的一篇关于内嵌汇编的介绍.关于常用的内嵌汇编(AT ...
- 图文混排--CoreText的简单运用
常见的在一些微博微信中可以看见一段文字中有不同的字体,字体有不同的颜色,并且可能会有一些笑脸之类的表情,这些可以通过图文混排做到. 图文混排可以通过WebView和CoreText做到,其他还有别的方 ...