LEETCODE--LRU Cache

Source: Internet
Author: User

Description:

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

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

The main idea is to design an LRU-based cache, which is the last-used reservation.

There are several methods to implement LRU cache, the +HASHMAP structure implementation of the linked list, the implementation of likedhashmap (inheritance, composition), FIFO implementation.

See my blog for details:

The FIFO implementation of LIKEDHASHMAP is simple and efficient.

1  Public classLRUCache {2     3     Private intcapacity;4     5     PrivateJava.util.linkedhashmap<integer, integer> cache =NewJava.util.linkedhashmap<integer, integer> (capacity,0.75f,true) {6 @Override7         protected BooleanRemoveeldestentry (Map.entry<integer, integer>eldest) {8             returnSize () >capacity;9         }Ten     }; One      A      PublicLRUCache (intcapacity) { -          This. Capacity =capacity; -     } the      -      Public intGetintkey) { -Integer res =Cache.get (key); -         returnres==NULL? -1: res; +     } -      +      Public voidSetintKeyintvalue) { A cache.put (key, value); at     } -}

Online better answer code also has hundreds of lines, time is hundreds of milliseconds, so it seems that the JDK Linkedhashmap implementation is still very efficient.

It's best not to reinvent the wheel in unnecessary situations--the Great God

LEETCODE--LRU Cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.