leetcode233 数字1的个数
给定一个整数 n
,计算所有小于等于 n
的非负整数中数字 1
出现的个数。
思路详见袁厨公众号
class Solution {
public int countDigitOne(int n) {
//高位
int high =n;
//低位
int low = 0;
//位数(个十百千万...)
int num = 1;
//当前位数上的数值
int curr = 0;
//计数
int count = 0;
while(high!=0){
curr = high % 10;
high /=10;
if(curr == 0) count +=high*num;
else if(curr == 1) count +=high*num+1+low;
else count+=(high+1)*num;
low += curr*num;
num *= 10;
}
return count;
}
}
leetcode146 LRU 缓存机制
class LRUCache {
class DLinkedNode{
int key;
int value;
// 前驱结点
DLinkedNode prev;
// 后驱结点
DLinkedNode next;
public DLinkedNode(int key, int value){
this.value = value;
this.key = key;
}
public DLinkedNode(){};
}
// 双向链表头结点
private DLinkedNode head;
// 双向链表尾结点
private DLinkedNode tail;
// 当前存储量
private int size;
// 最大容量
private int capacity;
private Map<Integer, DLinkedNode> map = new HashMap<>();
public LRUCache(int capacity) {
this.capacity = capacity;
this.size = 0;
head = new DLinkedNode();
tail = new DLinkedNode();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
DLinkedNode node = map.get(key);
if(node==null){
return -1;
}
// 移动到头
removeToHead(node);
return node.value;
}
public void put(int key, int value) {
DLinkedNode node = map.get(key);
if(node!=null){
node.value = value;
removeToHead(node);
}else{
node = new DLinkedNode(key,value);
if(this.size>=capacity){
map.remove(tail.prev.key);
removeNode(tail.prev);
}else{
size++;
}
addNode(node);
map.put(key, node);
}
}
// 移动结点到链表头部方法
public void removeToHead(DLinkedNode node){
removeNode(node);
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
// 移除结点方法
public void removeNode(DLinkedNode node){
node.prev.next = node.next;
node.next.prev = node.prev;
}
// 增加结点
public void addNode(DLinkedNode node){
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
}