leetcode233 数字1的个数

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
思路详见袁厨公众号

  1. class Solution {
  2. public int countDigitOne(int n) {
  3. //高位
  4. int high =n;
  5. //低位
  6. int low = 0;
  7. //位数(个十百千万...)
  8. int num = 1;
  9. //当前位数上的数值
  10. int curr = 0;
  11. //计数
  12. int count = 0;
  13. while(high!=0){
  14. curr = high % 10;
  15. high /=10;
  16. if(curr == 0) count +=high*num;
  17. else if(curr == 1) count +=high*num+1+low;
  18. else count+=(high+1)*num;
  19. low += curr*num;
  20. num *= 10;
  21. }
  22. return count;
  23. }
  24. }

leetcode146 LRU 缓存机制

  1. class LRUCache {
  2. class DLinkedNode{
  3. int key;
  4. int value;
  5. // 前驱结点
  6. DLinkedNode prev;
  7. // 后驱结点
  8. DLinkedNode next;
  9. public DLinkedNode(int key, int value){
  10. this.value = value;
  11. this.key = key;
  12. }
  13. public DLinkedNode(){};
  14. }
  15. // 双向链表头结点
  16. private DLinkedNode head;
  17. // 双向链表尾结点
  18. private DLinkedNode tail;
  19. // 当前存储量
  20. private int size;
  21. // 最大容量
  22. private int capacity;
  23. private Map<Integer, DLinkedNode> map = new HashMap<>();
  24. public LRUCache(int capacity) {
  25. this.capacity = capacity;
  26. this.size = 0;
  27. head = new DLinkedNode();
  28. tail = new DLinkedNode();
  29. head.next = tail;
  30. tail.prev = head;
  31. }
  32. public int get(int key) {
  33. DLinkedNode node = map.get(key);
  34. if(node==null){
  35. return -1;
  36. }
  37. // 移动到头
  38. removeToHead(node);
  39. return node.value;
  40. }
  41. public void put(int key, int value) {
  42. DLinkedNode node = map.get(key);
  43. if(node!=null){
  44. node.value = value;
  45. removeToHead(node);
  46. }else{
  47. node = new DLinkedNode(key,value);
  48. if(this.size>=capacity){
  49. map.remove(tail.prev.key);
  50. removeNode(tail.prev);
  51. }else{
  52. size++;
  53. }
  54. addNode(node);
  55. map.put(key, node);
  56. }
  57. }
  58. // 移动结点到链表头部方法
  59. public void removeToHead(DLinkedNode node){
  60. removeNode(node);
  61. node.prev = head;
  62. node.next = head.next;
  63. head.next.prev = node;
  64. head.next = node;
  65. }
  66. // 移除结点方法
  67. public void removeNode(DLinkedNode node){
  68. node.prev.next = node.next;
  69. node.next.prev = node.prev;
  70. }
  71. // 增加结点
  72. public void addNode(DLinkedNode node){
  73. node.next = head.next;
  74. node.prev = head;
  75. head.next.prev = node;
  76. head.next = node;
  77. }
  78. }