leetcode 150道题 计划花两个月时候刷完,今天(第二十九天)完成了3道(59-61)150:
59.(146. LRU 缓存)题目描述:
请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
第一版(这个是个很经典的面试题,真的我之前就遇到过,但是今天还是忘了,用不是 o(1)的法子写了,我想到了Map和链表,但是没想到LinkedHashMap,就不放我这shit代码了,放一下最终版)
class LRUCache {Map<Integer,Integer> map;int size;public LRUCache(int capacity) {size=capacity;map=new LinkedHashMap<Integer,Integer>();}public int get(int key) {Integer value=map.get(key);if(value!=null){map.remove(key);map.put(key,value);return value.intValue();}return -1;}public void put(int key, int value) {if(map.containsKey(key)){map.remove(key);map.put(key,value);return ;}if(map.size()>=size){//LinkedHashMap 里面有一个双向链表,真的建议去看看怎么实现LRU,面试必有!Integer oldestKey = map.keySet().iterator().next();map.remove(oldestKey);}map.put(key,value);}
}
60.(104. 二叉树的最大深度)题目描述:
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
第一版(直接递归)
class Solution {public int maxDepth(TreeNode root) {if(root==null){return 0;}int left=maxDepth(root.left);int right=maxDepth(root.right);return Math.max(left,right)+1;}}
第二版(层次遍历,有一层高度就加一)
class Solution {public int maxDepth(TreeNode root) {if(root==null)return 0;//非递归int maxLen=0;Queue<TreeNode> queue=new LinkedList();queue.offer(root);while(!queue.isEmpty()){int currNum=queue.size();while(currNum!=0){TreeNode temp =queue.poll();if(temp.left!=null){queue.offer(temp.left);}if(temp.right!=null){queue.offer(temp.right);}currNum--;}maxLen++;}return maxLen;}
}
61.(100. 相同的树)题目描述:
给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
第一版(直接递归,这个没搞遍历。。)
class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {if(p==null&&q==null){return true;}if(p!=null&&q!=null&&p.val==q.val){return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);}return false;}
}
今天收获应该就是LRU吧。这个真的很重要,实现我感觉理解不了都要背下来。。。
第二十九天了,前几天人家放假我感冒发烧,今天到了上班时候我就好了,天选打工人。。
加油加油,早日跳槽!!!