利用一个特殊的站保存当前使用的各个页面的页面号,每当进程访问某页面时,便将该页面的页面号从占中移出,将它压入栈顶。因此,栈顶始终是最新被访问页面的编号,而栈底则是最近最久未使用页面的页面号。
1 package test1; 2 3 import java.util.Stack; 4 5 public class LeastRecentPage 6 { 7 private static Stack<Integer> cache; 8 9 // METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED 10 public static int lruCountMiss(int max_cache_size, int[] pages) { 11 12 int missCount = 0; 13 14 if (cache == null) { 15 cache = new Stack<Integer>(); 16 } 17 18 int length = pages.length; 19 for (int j = 0;j < length; j++){ 20 if(cache.contains(pages[j])){ 21 cache.removeElement(pages[j]); 22 cache.push(pages[j]); 23 }else { 24 if(cache.size() == max_cache_size){ 25 cache.remove(0); 26 cache.push(pages[j]); 27 missCount++; 28 }else if(cache.size() < max_cache_size){ 29 cache.push(pages[j]); 30 missCount++; 31 } 32 } 33 } 34 35 return missCount; 36 } 37 // METHOD SIGNATURE ENDS 38 39 public static void main(String[] args) { 40 int count = lruCountMiss(2,new int[]{2,3,1,3,2,1,4,3,2}); 41 System.out.println(count); 42 } 43 }
java 在util下提供了Stack类,其中包含主要的方法:(摘自java api)
1. push
public E push(E item)
addElement(item)
item
- the item to be pushed onto this stack.item
argument. Vector.addElement(E)
2. pop
public E pop()
EmptyStackException
- if this stack is empty.3. peek
public E peek()
EmptyStackException
- if this stack is empty.4. empty
public boolean empty()
true
if and only if this stack contains no items; false
otherwise.5. search
public int search(Object o)
o
- the desired object.-1
indicates that the object is not on the stack.原文:http://www.cnblogs.com/TGmoving/p/4842884.html