剑指Offer66道题和答案(Java完整版 面试必备)

这篇博客整理了《剑指Offer》中的66道算法题目,涵盖数组、链表、二叉树、栈、队列等多种数据结构和算法,包括查找、替换、链表操作、树的遍历、序列化二叉树等。通过Java实现,适合面试准备和算法复习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近忙着准备春招,复习完这个又复习那个。不过还是忙里偷闲,把剑指Offer这66道题目重新刷了一遍,收获还是很大的,下面贴出答案,又不懂的可以给我留言,博主会及时解答。
我的github
准备把春招复习的知识都整理到github上,一边是自己做个总结,一边也能供大家参考
——leetcode数据库19道题
——leetcode Top100题目和答案

以下摘自牛客网剑指Offer

文章目录

1.二维数组中的查找

题目描述

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
·
Solution

/**
* 从左上角开始搜索
* 若小于target值,则向下搜索
* 若大于target值,则向左搜索
*/
public class Solution {
   
    public boolean Find(int target, int [][] array) {
   
        if (array == null || array.length < 1) {
   
            return false;
        }

        int col = array[0].length - 1;
        int row = 0;
        while (col >= 0 && row < array.length) {
   
            if (array[row][col] == target) {
   
                return true;
            }
            if (array[row][col] < target) {
    // 向下移动,寻找更大的元素
                row++;
            } else {
    // 向左移动,寻找更小的元素
                col--;
            }
        }
        return false;
    }
}

2.替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

Solution

/**
* 遍历字符串,用StringBuilder拼接出新的字符串
*/
public class Solution {
   
    public String replaceSpace(StringBuffer str) {
   
    	if (str == null || str.length() == 0) {
   
            return "";
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
   
            sb.append(str.charAt(i) == ' ' ? "%20" : str.charAt(i));
        }
        return sb.toString();
    }
}

3.从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

结点定义如下:

public class ListNode {
   
    int val;
    ListNode next = null;

    ListNode(int val) {
   
        this.val = val;
    }
}

Solution

import java.util.*;
public class Solution {
   
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
   
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> list = new ArrayList<>();
        while (listNode != null) {
   
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while (!stack.isEmpty()) {
   
            list.add(stack.pop());
        }
        return list;
    }
}

4.重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

结点定义如下:

public class TreeNode {
   
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
    val = x; }
}

Solution

public class Solution {
   
    private Map<Integer, Integer> map = new HashMap<>();
    
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
   
        if (pre.length != in.length || pre.length == 0) {
   
            return null;
        }
        for(int i = 0; i < in.length; i++) {
   
            map.put(in[i], i);
        }
        return rebuild(pre, in, 0, pre.length - 1, 0, in.length - 1);
    }

    private TreeNode rebuild(int[] pre, int[] in, int ps, int pe, int is, int ie) {
   
        if (ps > pe || is > ie) {
   
            return null;
        }
        TreeNode root = new TreeNode(pre[ps]);
        int index = map.get(pre[ps]);
        root.left = rebuild(pre, in, ps + 1, index - is + ps, is, index);
        root.right = rebuild(pre, in, index - is + ps + 1, pe, index + 1, ie);
        return root;
    }
}

5.用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的push和pop操作。 队列中的元素为int类型。

Solution

import java.util.Stack;

public class Solution {
   
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
   
        stack1.push(node);
    }
    
    public int pop() {
   
        if (stack2.isEmpty()) {
   
            while (!stack1.isEmpty()) {
   
                stack2.push(stack1.pop());
            }
        }
        
        return stack2.pop();
    }
}

6.旋转数组的最小数字

题目描述

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

Solution

public class Solution {
   
    public int minNumberInRotateArray(int [] array) {
   
        if (array.length == 0) {
   
            return 0;
        }
        int l = 0, r = array.length - 1;
        while (l < r) {
   
            int m = l + r >> 1;
            if (array[m] < array[array.length - 1]) {
   
                r = m;
            } else {
   
                l = m + 1;
            }
        }
        return array[l];
    }
}

7.斐波那切数列

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。

n<=39

Solution

/**
* 用递归当n很大时容易StackOverflowError
* 这里采用迭代法:
* F(n) = F(n - 1) + F(n - 2);
*/
public class Solution {
   
    public int Fibonacci(int n) {
   
        if (n < 1) {
   
            return n;
        }
        int pre = 0, cur = 1;
        for (int i = 1; i < n; i++) {
   
            int temp = cur;
            cur += pre;
            pre = temp;
        }
        return cur;
    }
}

8.跳台阶

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

Solution

/**
* 仔细分析可以发现本题能转化为斐波那契数列第n项值的问题
*/
public class Solution {
   
    public int JumpFloor(int target) {
   
        int pre = 0;
        int res = 1;
        
        for (int i = 0; i < target; i++) {
   
            int temp = res;
            res += pre;
            pre = temp;
        }
        
        return res;
    }
}

9.变态跳台阶

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

Solution

/**
* 每个台阶都有跳与不跳两种情况(除了最后一个台阶),最后一个台阶必须跳。所以共用2^(n-1)中情况
*/
public class Solution {
   
    public int JumpFloorII(int target) {
   
        return 1 << (target - 1);
    }
}

10.矩阵覆盖

题目描述

我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

Solution

/**
* 通过分析发现其依旧是斐波那契问题
*/
public class Solution {
   
    public int RectCover(int target) {
   
        if (target < 4) {
   
            return target;
        }
        
        int pre = 2;
        int res = 3;
        
        for (int i = 3; i < target; i++) {
   
            int temp = res;
            res += pre;
            pre = temp;
        }
        
        return res;
    }
}

11.二进制中1的个数

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

Solution

public class Solution {
   
    public int NumberOf1(int n) {
   
        int res = 0;
        while (n != 0) {
   
            res++;
            n &= (n - 1);
        }
        return res;
    }
}

12.数值的整数次方

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

Solution

public class Solution {
   
    public double Power(double base, int exponent) {
   
        if (exponent == 0) {
   
            return 1;
        }
        if (exponent == 1) {
   
            return base;
        }
        boolean isNegative = exponent < 0;
        exponent = Math.abs(exponent);
        double res = Power(base * base, exponent >>> 1);
        if ((exponent & 1) != 0) {
   
            res *= base;
        }
        return isNegative ? 1 / res : res;
    }
}

13. 调整数组顺序使奇数位于偶数前面

题目描述

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

Solution

public class Solution {
   
    public void reOrderArray(int [] array) {
   
        int[] temp = array.clone();
        int oddIndex = 0;
        int evenIndex = 0;
        for (int i = 0; i < array.length; i++) {
   
            if ((array[i] & 1) == 1) {
   
                evenIndex++;
            }
        }
        
        for (int i = 0; i < temp.length; i++) {
   
            if ((temp[i] & 1) == 1) {
   
                array[oddIndex++] = temp[i];
            } else {
   
                array[evenIndex++] = temp[i];
            }
        }
    }
}

14.链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

结点定义如下:

public class ListNode {
   
    int val;
    ListNode next = null;

    ListNode(int val) {
   
        this.val = val;
    }
}

Solution

public class Solution {
   
    public ListNode FindKthToTail(ListNode head,int k) {
   
        ListNode fast = head;
        ListNode slow = head;
        for (int i = 0; i < k; i++) {
   
            if (fast == null) {
   
                return null;
            }
            fast = fast.next;
        }
        while (fast != null) {
   
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

15.反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

结点定义如下:

public class ListNode {
   
    int val;
    ListNode next = null;

    ListNode(int val) {
   
        this.val = val;
    }
}

Solution

/**
* 头插法
*/
public class Solution {
   
    public ListNode ReverseList(ListNode head) {
   
        ListNode dummy = new ListNode(0);
        while (head != null) {
   
            ListNode next = head.next;
            head.next = dummy.next;
            dummy.next = head;
            head = next;
        }
        return dummy.next;
    }
}

16.合并两个排序链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

结点定义如下:

public class ListNode {
   
    int val;
    ListNode next = null;

    ListNode(int val) {
   
        this.val = val;
    }
}

Solution

public class Solution {
   
    public ListNode Merge(ListNode list1,ListNode list2) {
   
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;
        while (list1 != null && list2 != null) {
   
            if (list1.val < list2.val) {
   
                pre.next = list1;
                list1 = list1.next;
            } else {
   
                pre.next = list2;
                list2 = list2.next;
            }
            pre = pre.next;
        }
        pre.next = list1 == null ? list2 : list1;
        return dummy.next;
    }
}

17.树的子结构

题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

结点定义如下:

public class TreeNode {
   
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    TreeNode(int val) {
   
        this.val = val;
    }
}

Solution

public class Solution {
   
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
   
        if (root1 == null || root2 == null) {
   
            return false;
        }
        return isSubtree(root1, root2) 
            || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
    }
    
    private boolean isSubtree(TreeNode root1, TreeNode root2) {
   
        if (root2 == null) {
   
            return true;
        }
        if (root1 == null) {
   
            return false;
        }
        return root1.val == root2.val 
            && isSubtree(root1.left, root2.left) && isSubtree(root1.right, root2.right);
    }
}

18.二叉树的镜像

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

结点定义如下:

public class TreeNode {
   
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    TreeNode(int val) {
   
        this.val = val;
    }
}

Solution

public class Solution {
   
    public void Mirror(TreeNode root) {
   
        if (root == null) {
   
            return;
        }
        
        TreeNode left = root.left;
        root.left = root.right;
        root.right = left;
        Mirror(root.left);
        Mirror(root.right);
    }
}

19.顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

Solution

public class Solution {
   
    public ArrayList<Integer> printMatrix(int [][] matrix) {
   
        ArrayList<Integer> res = new  ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
   
            return res;
        }
        
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值