剑指offer之3-10题解
生活随笔
收集整理的這篇文章主要介紹了
剑指offer之3-10题解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
劍指offer之3-10題解
前言:
最近開始刷牛客的劍指offer,把刷過的題,代碼總結一下。有參考網上的代碼,一起加油。
目錄
3. 從尾到頭打印鏈表
(一)題目描述
(二) 思路
(三)代碼實現
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; import java.util.Stack; public class Solution {public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {Stack<Integer> stack = new Stack<>();while (listNode!=null){stack.add(listNode.val);listNode = listNode.next;}ArrayList<Integer> list = new ArrayList<>();while (!stack.isEmpty()){list.add(stack.pop());}return list;} }4. 重建二叉樹
(一)題目描述
(二) 思路
(三)代碼實現(報錯,先跳過)
/*** Definition for binary tree* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ import java.util.HashMap; import java.util.Map; public class Solution {public class Solution {private Map<Integer,Integer> indexForInOrders = new HashMap<>();public TreeNode reConstructBinaryTree(int[] pre, int[] in) {for (int i = 0; i < in.length; i++) {indexForInOrders.put(in[i],i);}return reConstructBinaryTree(pre,0,pre.length-1,0);}public TreeNode reConstructBinaryTree(int[] pre, int preL,int preR,int inL) {if (preL>preR)return null;TreeNode root = new TreeNode(pre[preL]);int inIndex = indexForInOrders.get(root.val);int leftTreeSize = inIndex-inL;root.left = reConstructBinaryTree(pre,preL+1,preL+leftTreeSize,inL);root.right = reConstructBinaryTree(pre,preL+leftTreeSize+1,preR,inL+leftTreeSize+1);return root;} }5. 用兩個棧實現隊列
(一)題目描述
(二) 思路
(三)代碼實現
import java.util.Stack;public class Solution {Stack<Integer> stack1 = new Stack<>();Stack<Integer> stack2 = new Stack<>();public void push(int node) {stack1.push(node);}public int pop() {if (stack1.isEmpty() && stack2.isEmpty()) {throw new RuntimeException("隊列為null");} else if (stack2.isEmpty()) {while (!stack1.isEmpty()) {stack2.push(stack1.pop());}}return stack2.pop();} }6. 旋轉數組的最小數字
(一)題目描述
(二) 思路
(三)代碼實現
大佬代碼:
小白代碼:
public class Solution {public int minNumberInRotateArray(int [] array) {if (array.length==0){return 0;}int minIndex = 0;for (int i = 1; i < array.length; i++) {if (array[minIndex]>array[i]){minIndex = i;}}return array[minIndex];} }7. 斐波那契數列
(一)題目描述
斐波那契數列公式:
(二)思路
(三)代碼實現
8. 跳臺階
(一)題目描述
(二)思路
(三)代碼實現
9. 變態跳臺階
(一)題目描述
(二)思路
f(n-1) = f(n-2) + f(n-3) + … + f(0)
f(n) = f(n-1) + f(n-2) + … + f(0)
f(n) = 2 * f(n-1)
(三)代碼實現
public class Solution {public int JumpFloorII(int target) {if (target <= 2) {return target;}return 2 * JumpFloorII(target - 1);}}10. 矩陣覆蓋
(一)題目描述
(二)思路
(三)代碼實現
總結
以上是生活随笔為你收集整理的剑指offer之3-10题解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构与算法之BFPRT算法
- 下一篇: 剑指offer之11-15题解