新堆栈溢出,所以请不要介意问这个我小白方式。 我试图用链表实现LRU缓存,我看到这里其他实现使用LinkedHashMap的和其他的数据结构,但这种情况下,我试图创建一个使用链表最好的优化版本,因为我在一个技术被问回合。
我在这里限制缓存大小3
- 有什么办法可以更好地优化这个LRU实现?
还什么将是这个实现的时间复杂度? 不会是顺序O(N)的不考虑换环,其被简单地打印在链表中的值?
public class LRU { public static void main(String[] args) { LinkedList list = new LinkedList(); int[] feed = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1 }; for (int i = 0; i < feed.length - 1; i++) { if (list.size() <= 2) { list.add(feed[i]); System.out.println(); System.out.println("Added " + feed[i]); System.out.println("size of list is " + list.size()); System.out.print("this is list "); for (int k = 0; k < list.size(); k++) { System.out.print(" " + list.get(k)); } } System.out.println(); if (list.size() >= 3) { System.out.println(); System.out.println("feed is *" + feed[i + 1] + "*"); Integer value1 = (Integer) list.get(0); Integer value2 = (Integer) list.get(1); Integer value3 = (Integer) list.get(2); if ((feed[i + 1] != value1) || (feed[i + 1] != value2) || (feed[i + 1] != value3)) { list.removeLast(); list.addLast(feed[i + 1]); list.set(0, value2); list.set(1, value3); list.set(2, feed[i + 1]); } if (feed[i + 1] == value1) { list.removeLast(); list.addLast(value1); list.removeFirst(); list.addFirst(value2); list.set(1, value3); } if (feed[i + 1] == value2) { list.removeLast(); list.addLast(value2); list.set(1, value3); list.removeFirst(); list.addFirst(value1); } if (feed[i + 1] == value3) { list.set(0, value1); list.set(1, value2); } } System.out.println("Current elements in cache at " + i); for (int t = 0; t < list.size(); t++) { System.out.print(" " + list.get(t)); } System.out.println(); } System.out.println(); System.out.println("------------------------------"); System.out.println("current elements in cache "); for (int i = 0; i < list.size(); i++) { System.out.print(" " + list.get(i)); } } }