MyBitmap
public class MyBitmap {
//每一个word是一个long类型元素,对应64位二进制
private long[] words;
//bitmap的位数大小
private int size;
public MyBitmap(int size) {
this.size = size;
this.words = new long[(getWordIndex(size-1) + 1)];
}
/**
* 判断bitmap某一位的状态
* @param bitIndex 位图的第bitIndex位
*/
public boolean getBit(int bitIndex) {
if(bitIndex<0 || bitIndex>size-1){
throw new IndexOutOfBoundsException("超过bitmap有效范围");
}
int wordIndex = getWordIndex(bitIndex);
return (words[wordIndex] & (1L << bitIndex)) != 0;
}
/**
* 把bitmap某一位设为真
* @param bitIndex 位图的第bitIndex位
*/
public void setBit(int bitIndex) {
if(bitIndex<0 || bitIndex>size-1){
throw new IndexOutOfBoundsException("超过bitmap有效范围");
}
int wordIndex = getWordIndex(bitIndex);
words[wordIndex] |= (1L << bitIndex);
}
/**
* 定位bitmap某一位所对应的word
* @param bitIndex 位图的第bitIndex位
*/
private int getWordIndex(int bitIndex) {
//右移6位,相当于除以64
return bitIndex >> 6;
}
public static void main(String[] args) {
MyBitmap bitMap = new MyBitmap(128);
bitMap.setBit(126);
bitMap.setBit(75);
System.out.println(bitMap.getBit(126));
System.out.println(bitMap.getBit(78));
}
}
LRUCache算法
import java.util.HashMap;
public class LRUCache {
private Node head;
private Node end;
//缓存存储上限
private int limit;
private HashMap<String, Node> hashMap;
public LRUCache(int limit) {
this.limit = limit;
hashMap = new HashMap<String, Node>();
}
public String get(String key) {
Node node = hashMap.get(key);
if (node == null){
return null;
}
refreshNode(node);
return node.value;
}
public void put(String key, String value) {
Node node = hashMap.get(key);
if (node == null) {
//如果key不存在,插入key-value
if (hashMap.size() >= limit) {
String oldKey = removeNode(head);
hashMap.remove(oldKey);
}
node = new Node(key, value);
addNode(node);
hashMap.put(key, node);
}else {