LeetCode设计实现题(一)

一、LRU缓存机制(LeetCode-146)

1.1 题目描述

1.2 解题思路

思路1:

使用Map存放key,value,使用List存放key和count,count为最新的index值,每次put、get操作都会使index自增。

进行put操作时,如果发现超过容量值capacity,则对list中的count排序,map和list都删除掉index最小的元素。(提示超时)

思路2:

使用LinkedList,每次put操作或get操作,当list中没有该key的元素的时候,且不超过容量时,直接插入元素,若有则删除key对应的原有元素,插入key对应的新元素值。

如果超过容量,则删除第一个元素,再添加进去。(通过)

1.3 解题代码

思路1:


public class LRUCache {

    private Map<Integer, Integer> map = null;
    private List<HitCount> list = null;
    private Map<Integer, HitCount> locationMap = null;
    private int index = 0;
    private int capacity = 0;

    public LRUCache(int capacity) {
        map = new HashMap<>(capacity);
        list = new LinkedList<>();
        locationMap = new HashMap<>(capacity);
        this.capacity = capacity;
    }

    public int get(int key) {
        //先找到key-value
        Integer value = map.get(key);
        if (value == null) {
            return -1;
        }

        HitCount h = locationMap.get(key);
        h.setCount(++index);
        return value;
    }

    public void put(int key, int value) {
        //若key已存在
        Integer existValue = map.get(key);
        //容量不充足
        if (existValue == null && map.size() == capacity) {
            //找到命中次数最少的一个、若命中次数相同,则去除插入最早的
            HitCount leastKey = getLeastKey();
            map.remove(leastKey.getKey());
            list.remove(leastKey);
            locationMap.remove(leastKey.getKey());
        }
        HitCount h = null;
        if (existValue != null) {
            h = locationMap.get(key);
            h.setCount(++index);
        } else {
            h = new HitCount(key, ++index);
            list.add(h);
        }
        map.put(key, value);
        locationMap.put(key, h);
        index++;
    }

    private HitCount getLeastKey() {
        list = list.stream().sorted((u1, u2) -> (u1.getCount() - u2.getCount())).collect(Collectors.toList());
        return list.get(0);
    }

    class HitCount {
        private int key;
        private int count;

        HitCount(int key, int count) {
            this.key = key;
            this.count = count;
        }

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

    }

}

思路2:


public class LRUCache {

    private List<LRUMap> list = null;
    private int capacity = 0;

    public LRUCache(int capacity) {
        list = new LinkedList<>();
        this.capacity = capacity;
    }

    public int get(int key) {
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            LRUMap node = (LRUMap) iterator.next();
            if (node.getKey() == key) {
                int value = node.getValue();
                list.remove(node);
                list.add(new LRUMap(key, value));
                return value;
            }
        }
        return -1;
    }

    public void put(int key, int value) {
        LRUMap node = new LRUMap(key, value);

        //查看该节点是否存在
        if (list.contains(node)) {
            list.remove(node);
        }
        //如果超过容量
        if (list.size() == capacity) {
            list.remove(0);
        }
        list.add(node);

    }

    class LRUMap {

        private int key;
        private int value;

        public LRUMap(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj == null || obj.getClass() != this.getClass()) {
                return false;
            }

            LRUMap map = (LRUMap) obj;
            return key == map.key;
        }
    }

}

原文地址:https://www.cnblogs.com/fonxian/p/11484158.html

时间: 2024-10-21 01:50:55

LeetCode设计实现题(一)的相关文章

LeetCode 第 73 题 (Set Matrix Zeroes)

LeetCode 第 73 题 (Set Matrix Zeroes) Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Follow up: Did you use extra space? A straight forward solution using O(mn) space is probably a bad idea. A simple impro

leetcode中第一题twosum问题解答算法的可行性证明

leetcode中第一题twosum问题解答算法的可行性证明 一.引入 关于leetcode中第一题twosum问题,网上已有不少高人做出过解答,并提出了切实可行的算法实现.我在解答该题时参考了博客http://www.zixue7.com/article-9576-1.html的解答.为让读者更直观地阅读和理解本文,先简要摘录以上博客的内容如下: 题目还原 Two Sum Given an array of integers, find two numbers such that they a

Leetcode第五题_Longest Palindromic Substring

Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. Leetcode第5题,题目大概意思是给一个字符串,从中找出最长的回文串,所谓回文串,就是

LeetCode 第三题,Longest Substring Without Repeating Characters

题目: Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest s

leetcode第9题-Palindrom Number

这是leetcode的第九题,相对来说比较简单,目的很简单,就是判断一个int型的数是不是回文数.但是有几点需要考虑: 负数应该没有回文数,要加判断!要注意额外的空间申请问题.判断是否是回文数势必要对一个数进行反转,反转的时候就要考虑溢出的问题.实现的代码如下: #include<stdio.h> bool isPalindrom(int x) { if(x<0) return false; else { int tmp=x; int sum=0; while(tmp) { sum=su

LeetCode 第 19 题 (Remove Nth Node From End of List)

LeetCode 第 19 题 (Remove Nth Node From End of List) Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the li

LeetCode 第 342 题(Power of Four)

LeetCode 第 342 题(Power of Four) Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return true. Given num = 5, return false. Follow up: Could you solve it without loops/recursion? 题目很简单,

LeetCode第四题,Add Two Numbers

题目原文: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6

LeetCode 第 342 题(Power of Four)

LeetCode 第 342 题(Power of Four) Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return true. Given num = 5, return false. Follow up: Could you solve it without loops/recursion? 题目非常eas