当前位置:网站首页>2022.02.13 - NC003. Design LRU cache structure

2022.02.13 - NC003. Design LRU cache structure

2022-07-06 08:21:00 A CAI continues to work hard

1. subject

 Insert picture description here
 Insert picture description here

2. Ideas

(1) HashMap+ queue

  • utilize HashMap Store key value pair data , Using queues to control the replacement of data .

3. Code

import java.util.*;

public class Test {
    
    public static void main(String[] args) {
    
    }
}

class Solution {
    
    public int[] LRU(int[][] operators, int k) {
    
        Map<Integer, Integer> map = new HashMap<>();
        Queue<Integer> queue = new LinkedList<>();
        int[] res = new int[operators.length];
        int index = 0;
        for (int i = 0; i < operators.length; i++) {
    
            switch (operators[i][0]) {
    
                case 1:
                    map.put(operators[i][1], operators[i][2]);
                    queue.offer(operators[i][1]);
                    if (queue.size() > k) {
    
                        map.remove(queue.poll());
                    }
                    break;
                case 2:
                    if (map.containsKey(operators[i][1])) {
    
                        res[index++] = map.get(operators[i][1]);
                        queue.remove(operators[i][1]);
                        queue.offer(operators[i][1]);
                    } else {
    
                        res[index++] = -1;
                    }
                    break;
            }
        }
        return Arrays.copyOfRange(res, 0, index);
    }
}
原网站

版权声明
本文为[A CAI continues to work hard]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131832390411.html