剑指offer题目汇总及解答

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/qq_24095055/article/details/90641117

数组中重复的数字

题目链接
题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

解题思路

利用HashSet判断是否已有该数据,有的话返回,没有的话添加。

解答代码

public boolean duplicate(int[] nums, int length, int[] duplication) {
    if(nums == null || nums.length <= 0){
        return false;
    }
    HashSet hashSet = new HashSet();
    for (int i = 0 ; i < nums.length ; i ++){
        if (hashSet.contains(nums[i])){
            duplication[0] = nums[i];
            return true;
        }else{
            hashSet.add(nums[i]);
        }
    }
    return false;
}

二维数组中的查找

题目链接
题目描述

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

解题思路

该二维数组中的一个数,小于它的数一定在其左边,大于它的数一定在其下边。因此,从右上角开始查找,就可以根据 target 和当前元素的大小关系来缩小查找区间,当前元素的查找区间为左下角的所有元素。

解答代码

public class Solution {

    public static void main(String[] args) {
        int[][] array = {{1,4,7},{2,5,6},{3,6,9}};
        System.out.println(Find(6,array));
    }
    public static boolean Find(int target, int [][] matrix) {
        if (matrix == null || matrix.length <= 0 || matrix[0].length <= 0){
            return false;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int r = 0;
        int c = col - 1;
        while(r < row && c >= 0){
            if (target == matrix[r][c]){
                return true;
            }else if (target < matrix[r][c]){
                c --;
            }else{
                r ++;
            }
        }
        return false;
    }
}

替换空格

题目链接
题目描述

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

解题思路

首先遍历字符串,当字符为空格时,在字符串尾部拼接两个字符(因为从' '变成'%20'要多两个字符长度),定义旧字符串的长度oldCount和新长度newCount,可以想到在我们完成替换后,oldCount应该是等于newCount的,所以while条件可以确定,具体解答如下:

解答代码

public class Solution {

    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        sb.append("we are superman");
        System.out.println(new Solution().replaceSpace(sb));
    }

    public String replaceSpace(StringBuffer str) {
        int oldCount = str.length() - 1;
        for (int i = 0 ; i <= oldCount ; i ++){
            if (str.charAt(i) == ' '){
                str.append("  ");
            }
        }
        int newCount = str.length() - 1;
        while (oldCount >= 0 && newCount >= oldCount){
            if (str.charAt(oldCount) == ' '){
                str.setCharAt(newCount--,'0');
                str.setCharAt(newCount--,'2');
                str.setCharAt(newCount--,'%');
            }else{
                str.setCharAt(newCount--, str.charAt(oldCount));
            }
            oldCount --;
        }
        return str.toString();
    }
}

从尾到头打印链表

题目链接
题目描述

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

解题思路

将链表里的值存放在一个列表中,再将列表反转输出

解答代码

/**
 *    public class ListNode {
 *        int val;
 *        ListNode next = null;
 *
 *        ListNode(int val) {
 *            this.val = val;
 *        }
 *    }
 *
 */
import java.util.ArrayList;
public class Solution {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(3);
        listNode.next = listNode1;
        listNode1.next = listNode2;
        ArrayList<Integer> array = new Solution().printListFromTailToHead(listNode);
        for (int i = 0 ; i < array.size() ; i ++)
            System.out.println(array.get(i));
    }

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        ArrayList<Integer> array = new ArrayList<>();
        while (listNode != null){
            arrayList.add(listNode.val);
            listNode = listNode.next;
        }
        for (int index = arrayList.size() - 1 ; index >=0 ; index --){
            array.add(arrayList.get(index));
        }
        return array;
    }
}

class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
       this.val = val;
   }
}

使用栈

栈具有后进先出的特点,在遍历链表时将值按顺序放入栈中,最后出栈的顺序即为逆序。

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    Stack<Integer> stack = new Stack<>();
    while (listNode != null) {
        stack.add(listNode.val);
        listNode = listNode.next;
    }
    ArrayList<Integer> ret = new ArrayList<>();
    while (!stack.isEmpty())
        ret.add(stack.pop());
    return ret;
}

重建二叉树

题目链接
题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
在这里插入图片描述
解题思路

前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。

解答代码

import java.util.HashMap;
import java.util.Map;

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public static void main(String[] args) {

    }
    // 缓存中序遍历数组每个值对应的索引
    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);
    }

    private 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;
    }
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

二叉树的下一个结点

题目链接
题目描述

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

解题思路

  1. 如果一个节点的右子树不为空,那么该节点的下一个节点是右子树的最左节点;
  2. 否则,向上找第一个左链接指向的树包含该节点的祖先节点。

解答代码

/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        if (pNode.right != null){
            TreeLinkNode rNode = pNode.right;
            while(rNode.left != null){
                rNode = rNode.left;
            }
            return rNode;
        }else{
            while (pNode.next != null){
                TreeLinkNode parent = pNode.next;
                if (parent.left == pNode){
                    return parent;
                }
                pNode = pNode.next;
            }
        }
        return null;
    }
}

class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

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

用两个栈实现队列

题目链接
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

解题思路

stack1 栈用来处理入栈(push)操作,stack2 栈用来处理出栈(pop)操作。一个元素进入 stack1 栈之后,出栈的顺序被反转。当元素要出栈时,需要先进入 stack2栈,此时元素出栈顺序再一次被反转,因此出栈顺序就和最开始入栈顺序是相同的,先进先出,这就是队列的顺序。

解答代码

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() throws Exception{
        if (stack2.isEmpty()){
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        if (stack2.isEmpty()){
            throw new Exception("queue is empty");
        }
        return stack2.pop();
    }
}

斐波那契数列

题目链接
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
在这里插入图片描述
解题思路
斐波那契的值除了第一个和第二个数值外,其他的均为前两个数值的和。
解答代码

public class Solution {
    public int Fibonacci(int n) {
        int a = 1,b=1,c=0;
        if (n <= 0){
            return 0;
        }else if (n == 1 || n == 2){
            return 1;
        }else{
            for (int i = 3 ; i <= n ; i ++){
                c = a + b;
                a = b;
                b = c;
            }
            return c;
        }
    }
}

矩形覆盖

题目链接
题目描述
我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
解题思路
当 n 为 1 时,只有一种覆盖方法:
在这里插入图片描述
当 n 为 2 时,有两种覆盖方法:
在这里插入图片描述
要覆盖 2n 的大矩形,可以先覆盖 21 的矩形,再覆盖 2*(n-1) 的矩形;或者先覆盖 22 的矩形,再覆盖 2(n-2) 的矩形。而覆盖 2*(n-1) 和 2*(n-2) 的矩形可以看成子问题。该问题的递推公式如下:
在这里插入图片描述
解答代码

public class Solution {
    public int RectCover(int n) {
        if (n <= 2)
            return n;
        int pre2 = 1, pre1 = 2;
        int result = 0;
        for (int i = 3; i <= n; i++) {
            result = pre2 + pre1;
            pre2 = pre1;
            pre1 = result;
        }
        return result;
    }
}

跳台阶

题目链接
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
解题思路
当 n = 1 时,只有一种跳法:
在这里插入图片描述
当 n = 2 时,有两种跳法:
在这里插入图片描述
跳 n 阶台阶,可以先跳 1 阶台阶,再跳 n-1 阶台阶;或者先跳 2 阶台阶,再跳 n-2 阶台阶。而 n-1 和 n-2 阶台阶的跳法可以看成子问题,该问题的递推公式为:
在这里插入图片描述
解答代码

public class Solution {
    public int JumpFloor(int n) {
        if (n <= 2)
            return n;
        int pre2 = 1, pre1 = 2;
        int result = 1;
        for (int i = 2; i < n; i++) {
            result = pre2 + pre1;
            pre2 = pre1;
            pre1 = result;
        }
        return result;
    }
}

变态跳台阶

题目链接
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解题思路
动态规划

import java.util.Arrays;

public class Solution {
    public int JumpFloorII(int target) {
        int[] dp = new int[target];
        Arrays.fill(dp, 1);
        for (int i = 1; i < target; i++)
            for (int j = 0; j < i; j++)
                dp[i] += dp[j];
        return dp[target - 1];
    }
}

数学推导:
跳上 n-1 级台阶,可以从 n-2 级跳 1 级上去,也可以从 n-3 级跳 2 级上去…,那么

f(n-1) = f(n-2) + f(n-3) + … + f(0)

同样,跳上 n 级台阶,可以从 n-1 级跳 1 级上去,也可以从 n-2 级跳 2 级上去… ,那么

f(n) = f(n-1) + f(n-2) + … + f(0)

综上可得

f(n) - f(n-1) = f(n-1)

f(n) = 2*f(n-1)

所以 f(n) 是一个等比数列

public int JumpFloorII(int target) {
return (int) Math.pow(2, target - 1);
}

旋转数组的最小数字

题目链接
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
解题思路
注意输入的是一个已经旋转过的,若是没有旋转过输出第一个值,因为是非递减(递增)数组,如果旋转过,遍历时很容易找到
解答代码

import java.util.ArrayList;
/**
 * 注意输入的是一个已经旋转过的,若是没有旋转过输出第一个值,因为是非递减(递增)数组,如果旋转过,遍历时很容易找到
 */
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        
        if(array.length==0){
            return 0;
        }
        if(array.length==1){
            return array[0];
        }
 
        for(int i=0;i<array.length-1;i++){
            // 前面的值大于后面的值,说明找到了反转的地方
            if(array[i]>array[i+1]){
                return array[i+1];
            }else{
                // 比对了倒数第二个值和最后一个值后说明没有反转,输出第一个值
                if(i==array.length-2){
                    return array[0];
                }
            }
        }
        return 0;
    }
}

矩阵中的路径 *

题目链接
题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
解题思路

  1. 根据给定数组,初始化一个标志位数组,初始化为false,表示未走过,true表示已经走过,不能走第二次
  2. 根据行数和列数,遍历数组,先找到一个与str字符串的第一个元素相匹配的矩阵元素,进入judge
  3. 根据i和j先确定一维数组的位置,因为给定的matrix是一个一维数组
  4. 确定递归终止条件:越界,当前找到的矩阵值不等于数组对应位置的值,已经走过的,这三类情况,都直接false,说明这条路不通
  5. 若k,就是待判定的字符串str的索引已经判断到了最后一位,此时说明是匹配成功的
  6. 下面就是本题的精髓,递归不断地寻找周围四个格子是否符合条件,只要有一个格子符合条件,就继续再找这个符合条件的格子的四周是否存在符合条件的格子,直到k到达末尾或者不满足递归条件就停止。
  7. 走到这一步,说明本次是不成功的,我们要还原一下标志位数组index处的标志位,进入下一轮的判断。

解答代码

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        //标志位,初始化为false
        boolean[] flag = new boolean[matrix.length];
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                 //循环遍历二维数组,找到起点等于str第一个元素的值,再递归判断四周是否有符合条件的----回溯法
                 if(judge(matrix,i,j,rows,cols,flag,str,0)){
                     return true;
                 }
            }
        }
        return false;
    }
     
    //judge(初始矩阵,索引行坐标i,索引纵坐标j,矩阵行数,矩阵列数,待判断的字符串,字符串索引初始为0即先判断字符串的第一位)
    private boolean judge(char[] matrix,int i,int j,int rows,int cols,boolean[] flag,char[] str,int k){
        //先根据i和j计算匹配的第一个元素转为一维数组的位置
        int index = i*cols+j;
        //递归终止条件
        if(i<0 || j<0 || i>=rows || j>=cols || matrix[index] != str[k] || flag[index] == true)
            return false;
        //若k已经到达str末尾了,说明之前的都已经匹配成功了,直接返回true即可
        if(k == str.length-1)
            return true;
        //要走的第一个位置置为true,表示已经走过了
        flag[index] = true;
         
        //回溯,递归寻找,每次找到了就给k加一,找不到,还原
        if(judge(matrix,i-1,j,rows,cols,flag,str,k+1) ||
           judge(matrix,i+1,j,rows,cols,flag,str,k+1) ||
           judge(matrix,i,j-1,rows,cols,flag,str,k+1) ||
           judge(matrix,i,j+1,rows,cols,flag,str,k+1)  )
        {
            return true;
        }
        //走到这,说明这一条路不通,还原,再试其他的路径
        flag[index] = false;
        return false;
    }
}

机器人的运动范围 *

题目链接
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解题思路
回溯法

  1. 从(0,0)开始走,每成功走一步标记当前位置为true,然后从当前位置往四个方向探索,
    返回1 + 4 个方向的探索值之和。
  2. 探索时,判断当前节点是否可达的标准为:
    1) 当前节点在矩阵内;
    2)当前节点未被访问过;
    3)当前节点满足limit限制。

解答代码

public class Solution {
    public int movingCount(int threshold, int rows, int cols) {
        boolean[][] visited = new boolean[rows][cols];
        return countingSteps(threshold,rows,cols,0,0,visited);
    }
    public int countingSteps(int limit,int rows,int cols,int r,int c,boolean[][] visited){
        if (r < 0 || r >= rows || c < 0 || c >= cols
                || visited[r][c] || bitSum(r) + bitSum(c) > limit)  return 0;
        visited[r][c] = true;
        return countingSteps(limit,rows,cols,r - 1,c,visited)
                + countingSteps(limit,rows,cols,r,c - 1,visited)
                + countingSteps(limit,rows,cols,r + 1,c,visited)
                + countingSteps(limit,rows,cols,r,c + 1,visited)
                + 1;
    }
    public int bitSum(int t){
        int count = 0;
        while (t != 0){
            count += t % 10;
            t /= 10;
        }
        return  count;
    }
}

二进制中 1 的个数

题目链接
题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
解题思路

如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。

举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。这个时候如果我们再把原来的整数和减去1之后的结果做与运算,从原来整数最右边一个1那一位开始所有位都会变成0。如1100&1011=1000.也就是说,把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。

解答代码

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

数值的整数次方

题目链接
题目描述

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

解题思路

下面的讨论中 x 代表 base,n 代表 exponent。

在这里插入图片描述

因为 (x*x)n/2 可以通过递归求解,并且每次递归 n 都减小一半,因此整个算法的时间复杂度为 O(logN)。

解答代码

public class Solution {
    public double Power(double base, int exponent) {
        if (exponent == 0)
            return 1;
        if (exponent == 1)
            return base;
        boolean isNegative = false;
        if (exponent < 0) {
            exponent = -exponent;
            isNegative = true;
        }
        double pow = Power(base * base, exponent / 2);
        if (exponent % 2 != 0)
            pow = pow * base;
        return isNegative ? 1 / pow : pow;
    }
}

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

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

思路1:类似冒泡算法,前偶后奇数就交换。
思路2:再创建一个数组,遍历旧数组,遇见偶数,就保存到新数组,同时从原数组中删除,最后将新数组的数添加到老数组。
因为思路2中的数组长度不好处理,可以考虑定义两个list,一个存放奇数一个存放偶数,最后遍历重新写入数组。

解答代码

//第一种方式,冒泡排序
public class Solution {
    public void reOrderArray(int [] array) {
        for (int i = 1 ; i < array.length ; i ++){
            for (int j = 0 ; j < array.length - i ; j ++){
                if (array[j] % 2 == 0 && array[j + 1] % 2 == 1){
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }
}
//第二种方式
import java.util.ArrayList;

public class Solution {
    public void reOrderArray(int [] array) {
        ArrayList<Integer> arrayList1 = new ArrayList<>();
        ArrayList<Integer> arrayList2 = new ArrayList<>();
        for (int i : array){
            if (i % 2 == 1){
                arrayList1.add(i);
            }else{
                arrayList2.add(i);
            }
        }
        int len = arrayList1.size();
        for (int i = 0 ;i < arrayList1.size() ; i ++){
            array[i] = arrayList1.get(i);
        }
        for (int i = 0 ;i < arrayList2.size() ; i ++){
            array[len + i] = arrayList2.get(i);
        }
    }
}

链表中倒数第k个结点

题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路

将节点依次存入一个列表中,最后输出列表中位置为列表长度减k的值(即为倒数第k个节点)
注意要先对输入的值校验,head是否为空,k是否大于零小于列表长度等

解答代码

import java.util.ArrayList;
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if (head == null){
            return null;
        }
        ArrayList<ListNode> list = new ArrayList<>();
        list.add(head);
        while(head.next != null){
            head = head.next;
            list.add(head);
        }
        if (k > list.size() || k <= 0)
            return null;
        return list.get(list.size() - k);
    }
}

反转链表

题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路

解答代码

猜你喜欢

转载自blog.csdn.net/qq_24095055/article/details/90641117