我试图使用LinkedHashMap实现LRU缓存.在LinkedHashMap(http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html)的文档中,它说:
请注意,如果将键重新插入地图,则插入顺序不会受到影响.
但是,当我做以下投入时
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private int size;
public static void main(String[] args) {
LRUCache<Integer, Integer> cache = LRUCache.newInstance(2);
cache.put(1, 1);
cache.put(2, 2);
cache.put(1, 1);
cache.put(3, 3);
System.out.println(cache);
}
private LRUCache(int size) {
super(size, 0.75f, true);
this.size = size;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
public static <K, V> LRUCache<K, V> newInstance(int size) {
return new LRUCache<K, V>(size);
}
}
Run Code Online (Sandbox Code Playgroud)
输出是
{1=1, 3=3}
Run Code Online (Sandbox Code Playgroud)
这表明重新插入确实影响了订单.有人知道任何解释吗?
我在hackerrank遇到了一个问题. https://www.hackerrank.com/challenges/countingsort4
由于超时,我的第一次尝试通过了除最后一个之外的所有测试用例.在未能提出更高效的算法之后,我通过使用StringBuilder而不是直接连接字符串来改进代码.这使得运行时间从5秒到3.5秒不等.
我的问题是,还有其他方法可以改善运行时间吗?谢谢.
以下是我的代码.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
scanner.nextLine();
int[] oriNum = new int[N];
String[] oriStr = new String[N];
int[] count = new int[100];
int[] indices = new int[100];
int[] output = new int[N];
// save the originals and the count array
for (int i = 0; i < N; i++) {
oriNum[i] = scanner.nextInt();
oriStr[i] = scanner.nextLine().trim();
count[oriNum[i]]++;
}
// accumulate the count …
Run Code Online (Sandbox Code Playgroud)