JavaScript 数组和map实现
设计LRU缓存结构
http://www.nowcoder.com/questionTerminal/e3769a5f49894d49b871c09cadd13a61
借助大佬的思路,map+list实现,觉得用Java有点麻烦,JavaScript30行搞定,开心了!
function LRU( operators , k ) { // write code here var map = new Map(); var list = []; var res = []; for(var item in operators){ var op = operators[item][0]; if(op===1){ map.set(operators[item][1],operators[item][2]); if(list.length>=k){ list.shift(); } list.push(operators[item][1]); }else if(op===2){ var key = operators[item][1]; var index = list.indexOf(key) if(index==-1){ res.push(-1); }else{ res.push(map.get(key)); list.splice(index,1); list.push(key); } } } return res } module.exports = { LRU : LRU };