problem0460

package
v0.0.0-...-899dd15 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2020 License: MIT Imports: 2 Imported by: 0

README

460. LFU Cache

题目

Design and implement a data structure for Least Frequently Used (LFU) 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 reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.

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

Example:

LFUCache cache = new LFUCache( 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.get(3);       // returns 3.
cache.put(4, 4);    // evicts key 1.
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

解题思路

见程序注释

100

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LFUCache

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

LFUCache 实现了 Least Frequently Used (LFU) cache

func Constructor

func Constructor(capacity int) LFUCache

Constructor 构建了 LFUCache

func (*LFUCache) Get

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

Get 获取 key 的值

func (*LFUCache) Put

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

Put 把 key, value 成对地放入 LFUCache 如果 LFUCache 已满的话,会删除掉 LFUCache 中使用最少的 key

type PQ

type PQ []*entry

PQ implements heap.Interface and holds entries.

func (PQ) Len

func (pq PQ) Len() int

func (PQ) Less

func (pq PQ) Less(i, j int) bool

func (*PQ) Pop

func (pq *PQ) Pop() interface{}

Pop 从 pq 中取出最优先的 entry

func (*PQ) Push

func (pq *PQ) Push(x interface{})

Push 往 pq 中放 entry

func (PQ) Swap

func (pq PQ) Swap(i, j int)

Jump to

Keyboard shortcuts

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