剑指offer一周目刷题

本文精选了22道经典算法题目,涵盖了从二维数组查找、字符串处理、链表操作到二叉树构造等核心数据结构与算法知识。每道题都提供了详细的代码实现,帮助读者深入理解算法原理及应用。

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

1. 二维数组中的查找

    public boolean Find(int target, int [][] array) {
        if (array == null) return false;
        // 从左下开始找,如果target大了,就往上找,如果target小了,就往右找
        int rows = array.length;
        int cols = array[0].length;
        int currow = rows-1;
        int curcol = 0;
        while ( currow>=0 && currow<rows && curcol>=0 && curcol<cols ) {
            if (target < array[currow][curcol]) {
                currow--;
            } else if (target > array[currow][curcol]) {
                curcol++;
            } else {
                return true;
            }
        }
        return false;
    }

2.替换空格

    public String replaceSpace(StringBuffer str) {
        StringBuffer out = new StringBuffer();
        for(int i=0; i<str.toString().length(); i++) {
            char tmp = str.charAt(i);
            if (String.valueOf(tmp).equals(" ")) {
                out.append("%20");
            } else {
                out.append(tmp);
            }
        }
        return out.toString();
    }

3.从尾到头打印链表

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<Integer>();
       helper(listNode, list);
        return list;
    }
    
    public void helper(ListNode listNode, ArrayList<Integer> list) {
        if (listNode == null) {
            return;
        }
        helper(listNode.next, list);
        list.add(listNode.val);
    }

4.重建二叉树

public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if (pre==null||in==null) return null;
        return helper(pre, 0, pre.length-1, in, 0, in.length-1);
    }
    
    public TreeNode helper(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd) {
        if (preStart>preEnd||inStart>inEnd) return null;
        TreeNode root = new TreeNode(pre[preStart]);
        for (int i=inStart; i<=inEnd; i++) {
            if (pre[preStart]==in[i]) {
                // 前序(中-左-右)和中序(左-中-右),所以 中-左 = 左-中 长度
                root.left = helper(pre, preStart+1, preStart-inStart+i, in, inStart, i-1);
                root.right = helper(pre, preStart-inStart+i+1, preEnd, in, i+1, inEnd);
                break;
            }
        }
        return root;
    }

5.用两个栈实现队列

    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.旋转数组的最小数字

    //TODO 有时间看看二分法
    public int minNumberInRotateArray(int [] array) {
        int min = 0;
        if ( array==null ) return min;
        for ( int i=1; i<array.length-1; i++ ) {
            if (array[i]<array[i-1]) {
                return array[i];
            }
        }
        return array[0];
    }

7.斐波那契队列

    public int Fibonacci(int n) {
         //TODO 可以考虑用动态规划
        if (n<=0) {
            return 0;
        } else if (n==1) {
            return 1;
        }
        return Fibonacci(n-1)+Fibonacci(n-2);
    }
    public int Fibonacci(int n) {
         // 用动态规划
        if (n<=1) return n;
        int[] record = new int[n+1];
        record[0] = 0;
        record[1] = 1;
        for (int i=2; i<=n; i++) {
            record[i] = record[i-1]+record[i-2];
        }
        return record[n];
    }

8.跳台阶

同7

9.变态跳台阶

    public int JumpFloorII(int target) {
        // 除了最后一个台阶,其余台阶均存在跳与不跳的情况,所以为2^(n-1)的情况。
         return  1<<--target;
    }

10.矩阵覆盖

同7

11.二进制中1的个数

    public int NumberOf1(int n) {
        // 要在看一遍
        int count = 0;
        for (int i=0; i<32; i++) {
            if (( n >> i & 1) == 1) {
                ++count;
            }
        }
        return count;
    }

12.数值的整数次方

    public double Power(double base, int exponent) {
        double base1 = base;
        // 分为次方大于0,小于0,等于0三种情况.为啥不直接用Math.pow/有空看看位移算
        if (exponent < 0) {
            for (int i = exponent - 1; i < 0; i++) {
                base1 = base1/base;
            }
        } else if (exponent > 0) {
            for (int i = 0; i<exponent-1; i++) {
                base1 = base1*base;
            } 
        }else {
            base1 = 1;
        }
        return base1;
  }

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

    public void reOrderArray(int [] array) {
        if (array == null) return;
        int k = 0;
        for (int i = 0; i<array.length; i++) {
            if ((array[i] & 1)==1) {
                for(int j=i; j>k; j--) {
                    int tmp = array[j];
                    array[j] = array[j-1];
                    array[j-1] = tmp;
                }
                k++;
            }
        }
    }

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

public ListNode FindKthToTail(ListNode head,int k) {
        // 要在看一遍
        if (k==0||head==null) return null;
        ListNode pHead = head;
        for (int i=0; i<k; i++) {
            if (pHead != null) {
                pHead = pHead.next;
            } else {
                return null;
            }
        }
        while (pHead!=null) {
            pHead = pHead.next;
            head = head.next;
        }
        return head;
    }

15.反转链表

public ListNode ReverseList(ListNode head) {
           if (head==null) return null;
           ListNode next = null;
           ListNode pre = null;
           while (head!=null) {
               // 存储下一个节点,防止链断裂
               next = head.next;
               // 反转链
               head.next = pre;
               // 为下次做准备
               pre = head;
               head = next;
           }
           return pre;

16.合并两个排序的链表

	public ListNode Merge(ListNode list1,ListNode list2) {
        if (list1==null) return list2;
        if (list2==null) return list1;
        if (list1.val<=list2.val) {
            list1.next = Merge(list1.next, list2);
            return list1;
        } else {
            list2.next = Merge(list1, list2.next);
            return list2;
        }
    }

17.树的子结构

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

18.二叉树镜像

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

19.顺时针打印矩阵

    ArrayList<Integer> list = new ArrayList<Integer>();
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        //TODO 这个要再看
        int rows = matrix.length;
        int cols = matrix[0].length;
        for (int i=0; rows>2*i&&cols>2*i; i++) {
            helper(matrix, rows, cols, i);
        }
        return list;
    }
    public void helper(int[][] matrix, int rows, int cols, int i) {
        // 打印从左到右
        for (int a=i; a<cols-i; a++) list.add(matrix[i][a]);
        // 打印从上到下
        for (int b=i+1; b<rows-i; b++) list.add(matrix[b][cols-i-1]);
        // 打印从右到左
        for (int c=cols-i-2; c>=i && rows - i - 1 > i; c--) list.add(matrix[rows-i-1][c]);
        // 打印从下到上
        for (int d=rows-i-2; d>=i+1 && cols - i - 1 > i; d--) list.add(matrix[d][i]);
    }

20.包含min函数的栈

	// 借助辅助栈
    Stack<Integer> stack = new Stack<Integer>();
    Stack<Integer> minStack = new Stack<Integer>();
    public void push(int node) {
        stack.push(node);
        if (minStack.isEmpty()||minStack.peek()>node) {
            minStack.push(node);
        }
    }
    
    public void pop() {
        if (stack.peek()==minStack.peek()) {
            minStack.pop();
        }
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return minStack.peek();
    }

21.栈的压入、弹出序列

    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer> stack = new Stack<Integer>();
        int i = 0;
        for (int a: pushA) {
            stack.push(a);
            while(!stack.isEmpty() && popA[i] == stack.peek()) {
                stack.pop();
                i++;
            }
        }
        
        return stack.isEmpty()?true:false;
    }

22.从上往下打印二叉树

    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if (root==null) return list;
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            if (tmp.left!=null) {
                queue.add(tmp.left);
            }
            if (tmp.right!=null) {
                queue.add(tmp.right);
            }
            list.add(tmp.val);
        }
        return list;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值