Advertisement
Guest User

Untitled

a guest
Oct 10th, 2015
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. /**
  2. * @constructor
  3. */
  4. var doubleLinkList = function(key, val){
  5. this.key = key
  6. this.val = val
  7. this.pre = null
  8. this.next = null
  9. }
  10.  
  11. var LRUCache = function(capacity) {
  12. this.map = {}
  13. this.capacity = capacity
  14. this.head = null
  15. this.tail = null
  16. };
  17.  
  18. /**
  19. * @param {number} key
  20. * @returns {number}
  21. */
  22. LRUCache.prototype.get = function(key) {
  23. if(!this.map.hasOwnProperty(key)){
  24. return -1
  25. }else{
  26. var node = this.map[key]
  27. this.removeNode(node)
  28. this.setTail(node)
  29. return node.val
  30. }
  31. };
  32.  
  33. LRUCache.prototype.removeNode = function(node){
  34. //在队头
  35. if(node.pre === null){
  36. this.head = node.next
  37. }else{
  38. //接前面
  39. node.pre.next = node.next
  40. }
  41. //在队尾
  42. if(node.next === null){
  43. this.tail = node.pre
  44. }else{
  45. //接后面
  46. node.next.pre = node.pre
  47. }
  48. }
  49.  
  50. LRUCache.prototype.setTail = function(node){
  51. if(this.tail === null){
  52. this.tail = node
  53. this.head = node
  54. node.pre = null
  55. }else{
  56. node.pre = this.tail
  57. this.tail.next = node
  58. this.tail = node
  59. }
  60. node.next = null
  61. }
  62.  
  63. /**
  64. * @param {number} key
  65. * @param {number} value
  66. * @returns {void}
  67. */
  68. LRUCache.prototype.set = function(key, value) {
  69. if(this.map.hasOwnProperty(key)){
  70. var node = this.map[key]
  71. this.removeNode(node)
  72. this.setTail(node)
  73. node.val = value
  74. }else{
  75. var node = new ListNode(key, value)
  76. if(Object.keys(this.map).length < this.capacity){
  77. this.setTail(node)
  78. }else{
  79. delete this.map[this.head.key]
  80. this.removeNode(this.head)
  81. this.setTail(node)
  82. }
  83. this.map[key] = node
  84. }
  85. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement