problem0146

package
v0.0.0-...-db5e768 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2019 License: MIT Imports: 1 Imported by: 0

README

146. LRU Cache

题目

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Follow up: Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

解题思路

LRU缓存利用了这样的一种思想。LRU是Least Recently Used 的缩写,翻译过来就是“最近最少使用”,也就是说,LRU缓存把最近最少使用的数据移除,让给最新读取的数据。而往往最常读取的,也是读取次数最多的,所以,利用LRU缓存,我们能够提高系统的performance.

见程序注释

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LRUCache

type LRUCache struct {
	// contains filtered or unexported fields
}

LRUCache contains a hash map and a doubly linked list

func Constructor

func Constructor(capacity int) LRUCache

Constructor initializes a new LRUCache.

func (*LRUCache) Get

func (c *LRUCache) Get(key int) int

Get a list node from the hash map.

func (*LRUCache) Put

func (c *LRUCache) Put(key int, value int)

Put key and value in the LRUCache

type Pair

type Pair struct {
	// contains filtered or unexported fields
}

Pair is the value of a list node.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL