TypechoJoeTheme

Toasobi的博客

搜索到 28 篇与 的结果 ———
2023-03-03

斐波那契数列(简单)

斐波那契数列(简单)
这道题上来一个递归,按道理应该是正确的,但是递归会超出时间限制、<div> class Solution { public int fib(int n) { int num = 0; if(n == 0) return 0; if(n == 1) return 1; //主函数 num += fib(n-1) + fib(n-2); return num; } } </div>下面来看不同的解决方法=========================滚动数组(动态规划)这里的滚动数组并不是真的数组,而是三个变量滚动赋值初始的时候是001,一次后是011,两次过后是112......<div> class Solution { public int fib(int n) { final int MOD = 1000000007; if (n < ...
2023-03-03

剑指offer(第二版)

0 阅读
0 评论
2023年03月03日
0 阅读
0 评论
2023-03-02

用两个栈实现队列(简单)

用两个栈实现队列(简单)
这题我就是正解!要注意LinkedList也可以当做栈使用,速度还比stack还快嘞<div> class CQueue { LinkedList<Integer> stack1; LinkedList<Integer> stack2; public CQueue() { stack1 = new LinkedList(); //输入栈 stack2 = new LinkedList(); //输出栈 } public void appendTail(int value) { stack1.push(value); } public int deleteHead() { if(stack1.isEmpty()){ //stack1为空 if(stack2.isEmpty()){ return -1; } ...
2023-03-02

剑指offer(第二版)

0 阅读
0 评论
2023年03月02日
0 阅读
0 评论
2023-03-02

重建二叉树(中等)

重建二叉树(中等)
这道题就是要你根据前序和中序遍历的结果让你构建一课二叉树这题当时我都不会做答案使用递归的方法,就是说当一个问题可以分为多次重复的子问题时,我们就应该想到递归,总结下来,该题就是通过分析两个遍历数组,运用map存中序对应的元素下标,先用前序找到根节点,再去map中对应下标,在中序数组中在根节点左边的就是左子树,右边就是右子树,然后循环这个任务,构建这棵数<div> class Solution { private Map<Integer, Integer> indexMap; public TreeNode myBuildTree(int[] preorder,int[] inorder,int pre_first,int pre_last, int in_first, int in_last){ //终止条件 if(pre_first>pre_last || in_first>in_last){ return null; } //...
2023-03-02

剑指offer(第二版)

0 阅读
0 评论
2023年03月02日
0 阅读
0 评论
2023-03-02

从尾到头打印链表(简单)

从尾到头打印链表(简单)
我这里用的是递归,时间和空间都很垃圾。。。<div> class Solution { List<Integer> array = new ArrayList<>(); public int[] reversePrint(ListNode head) { if(head == null){ int[]s=new int[0]; return s; } ListNode temp = head; goThrough(temp); return array.stream().mapToInt(Integer::intValue).toArray(); //List转int的array } public void goThrough(ListNode node){ if(node.next != null){ goThrough(node.next);...
2023-03-02

剑指offer(第二版)

0 阅读
0 评论
2023年03月02日
0 阅读
0 评论