剑指offer——Java版

本文整理了《剑指offer》中的部分Java编程面试题目,涵盖链表、数组、树、栈、队列、字符串、矩阵、二叉树等多种数据结构和算法问题,包括反转链表、寻找重复数字、实现队列、字符串排列、数组逆序对、找链表倒数第k个节点、数组旋转最小值、顺时针打印矩阵、重建二叉树、数组查找、斐波那契数列等,旨在帮助读者掌握和提高编程能力。

剑指offer——Java版

以下按照出现频率进行排序

常见的结构体定义

链表
public class ListNode {
   
   
     int val;
     ListNode next;
     ListNode(int x) {
   
    val = x; }
 }
 public class TreeNode {
   
   
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) {
   
    val = x; }
 }

24 反转列表

难度 重点度 知识点 掌握度 链接
简单 A 链表 已掌握 24 反转列表
  • 题目描述:
    定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
  • 示例
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
  • 解答
class Solution {
   
   
    public ListNode reverseList(ListNode head) {
   
   
        ListNode preNode = null;
        ListNode pNode = head;
        ListNode pNext;
        while(pNode != null){
   
   
            pNext = pNode.next;
            pNode.next = preNode;
            preNode = pNode;
            pNode = pNext;
        }
        return preNode;
    }
}
  • 知识点总结
    需要三个节点来存储前中后,且要保证pNode!=null的前提下才给next赋值

03 数组中重复的数字

难度 重点度 知识点 掌握度 链接
简单 A 数组 已掌握 03 数组中重复的数字
  • 题目描述:
    找出数组中重复的数字。
    在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
  • 示例
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3 
  • 解答
class Solution {
   
   
    public int findRepeatNumber(int[] nums) {
   
   
        for(int i = 0; i < nums.length; i++){
   
   
            while(nums[i] != i){
   
   
                if(nums[i] == nums[nums[i]]) return nums[i];
                int temp = nums[i];
                nums[i] = nums[temp];
                nums[temp] = temp;
            }
        }
        return -1;
    }
}
  • 知识点总结

09 用两个栈实现队列

难度 重点度 知识点 掌握度 链接
简单 A 队列、栈 已掌握 here
  • 题目描述:
    用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

  • 示例

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
  • 解答
class CQueue {
   
   
    //Deque<Integer> stk1 = new LinkedList<>();//所有的类型都是包装类
    //Deque<Integer> stk2 = new LinkedList<>();//也可以用Deque和LinkedList生成栈
    private Stack<Integer> stk1 = new Stack<>();
    private Stack<Integer> stk2 = new Stack<>();//前面的private绝对不能少,JAVA的Stack正常用  

    public CQueue() {
   
   

    }
    
    public void appendTail(int value) {
   
   
        stk1.push(value);
    }
    
    public int deleteHead() {
   
   
        if(stk2.empty()){
   
   
            while(!stk1.empty()){
   
   
                stk2.push(stk1.pop());
            }
        }
        if(stk2.empty()) return -1;
        return stk2.pop();
    }
}
  • 知识点总结

38 字符串的排列

难度 重点度 知识点 掌握度 链接
中等 A 回溯 here
  • 题目描述:
    输入一个字符串,打印出该字符串中字符的所有排列。
    你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
  • 示例
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
  • 解答
class Solution {
   
   
    List<String> res = new ArrayList<>();
    public String[] permutation(String s) {
   
   
        char[] arr = s.toCharArray();//arr使用来重新排序,减少下面找前面重复的
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        boolean[] used = new boolean[s.length()];
        backtrace(sb, used, arr);
        return res.toArray(new String[res.size()]);
    }

    private void backtrace(StringBuilder sb, boolean[] used, char[] arr){
   
   
        if(sb.length()==arr.length){
   
   
            res.add(sb.toString());
            return;
        }
        for(int i = 0; i < arr.length; i++){
   
   
            if(used[i]) continue;
            if(i > 0 && arr[i]==arr[i-1] && !used[i-1]) continue;//最后一处,在i和i-1相等时,如果上一个没用过,说明是上一个出现过,现在回溯,才导致上一个没的,否则,如果不同,必然会有
            used[i] = true;
            backtrace(sb.append(arr[i]), used, arr);
            sb.deleteCharAt(sb.length()-1);//StirngBuilder删除元素
            used[i] = false;
        }
    }
}
  • 知识点总结

51 数组中的逆序对

难度 重点度 知识点 掌握度 链接
困难 A 归并排序 https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
  • 题目描述:
    在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
  • 示例
输入: [7,5,6,4]
输出: 5
  • 解答
class Solution {
   
   
    int[] nums, tmp;
    public int reversePairs(int[] nums) {
   
   
        this.nums = nums;
        tmp = new int[nums.length];
        return mergeSort(0, nums.length-1);
    }

    private int mergeSort(int left, int right){
   
   
        if(left >= right) return 0;
        int mid = (left+right) >> 1;
        int res = mergeSort(left, mid) + mergeSort(mid+1, right);
        int i = left, j = mid + 1;//指向两个子队列的头
        for(int k = left; k <= right; k++) tmp[k] = nums[k];//先拷贝,在替换+统计
        for(int k = left; k <= right; k++) {
   
   //逐位寻找双指针队头的最小值,小的放这里
            if(i == mid + 1){
   
   
                nums[k] = tmp[j++];
            } else if (j == right + 1 || tmp[i] <= tmp[j]){
   
   //也要把j==right放前面,利用短路性防止越界
                nums[k] = tmp[i++];
            } else {
   
   //必须放最后,防止越界
                nums[k] = tmp[j++];
                res += mid + 1 - i;
            } 
        }
        return res;
    }
}
  • 知识点总结

22 链表中倒数第k个结点

难度 重点度 知识点 掌握度 链接
简单 已掌握 here
  • 题目描述:
    输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
    例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。
  • 示例
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
  • 解答
class Solution {
   
   
    public ListNode getKthFromEnd(ListNode head, int k) {
   
   
        if(head == null || k <= 0) return null;
        ListNode front = head;
        ListNode behind = head;
        while(k-->0 && front != null){
   
   
            front = front.next;
        }
        while(front != null){
   
   
            front = front.next;
            behind = behind.next;
        }
        return behind;
    }
}
  • 知识点总结

11 旋转数组的最小数

难度 重点度 知识点 掌握度 链接
简单 已掌握 here
  • 题目描述:
    把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
  • 示例
输入:[2,2,2,0,1]
输出:0
  • 解答
class Solution {
   
   
    public int minArray(int[] numbers) {
   
   
        
        int left = 0, right = numbers.length-1;
        while(left < right){
   
   
            int mid = (right + left) >> 1;//也可以left+(right-left)>>1;
            if(numbers[mid] < numbers[right]){
   
   
                right = mid;
            }
            else if(numbers[mid] > numbers[right]){
   
   
                left = mid + 1;
            }
            else right -= 1;//点睛之笔,右边一直往左,试着找最小,如果是找最大,应该向右走
        }
        return numbers[left];
    }
}
  • 知识点总结

29 顺时针打印矩阵

难度 重点度 知识点 掌握度 链接
简单 已掌握 here
  • 题目描述:
    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
  • 示例
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
  • 解答
class Solution {
   
   
    public int[] spiralOrder(int[][] matrix) {
   
   
        int m = matrix.length;
        if(m == 0) return new int[0];//二维数组要注意判断[],返回空数组new int[0]
        int n = matrix[0].length;
        int[] res = new int[m * n];
        int row = 0, col = 0, count = 0;
        while(true){
   
   
            for(int i = col; i < n; i++){
   
   
                res[count++] = matrix[row][i];
            }if(m == ++row) break;
            for(int i = row; i < m; i++){
   
   
                res[count++] = matrix[i][n-1];
            }if(--n == col) break;
            for(int i = n-1; i >= col; i--){
   
   
                res[count++] = matrix[m-1][i];
            }if(--m == row) break;
            for(int i = m-1; i >= row; i--){
   
   
                res[count++] = matrix[i][col];
            }if(n == ++col) break;
        }
        return res;
    }
}
  • 知识点总结

07 重建二叉树

难度 重点度 知识点 掌握度 链接
中等 A 树的遍历和递归
  • 题目描述:
    输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
    假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
  • 示例
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
  • 解答
class Solution {
   
   
    
    HashMap<Integer, Integer> in_map = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
   
   
        int n = inorder.length;
        if(n <= 0) return null;
        for(int i = 0; i <n; i++){
   
   
            in_map.put(inorder[i],i);
        }
        return findRoot(preorder, 0, 0, n-1);
    }

    private TreeNode findRoot(int[] preorder, int pre_root, int in_left, int in_right){
   
   
        if(in_left > in_right) return null;
        TreeNode root = new TreeNode(preorder[pre_root]);
        int in_root = in_map.get(root.val);

        root.left = findRoot(preorder, pre_root+1, in_left, in_root-1);
        root.right = findRoot(preorder, pre_root+in_root-in_left+1,in_root+1, in_right);
        
        return root;
    }
}
  • 知识点总结

06 从尾到头打链表

难度 重点度 知识点 掌握度 链接
简单 已掌握 here
  • 题目描述:
    输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
  • 示例
输入:head = [1,3,2]
输出:[2,3,1]
  • 解答
class Solution {
   
   
    public int[] reversePrint(ListNode head) {
   
   
        Stack<ListNode> stack = new Stack<>();
        ListNode temp = head;
        while(temp != null){
   
   
            stack.push(temp);//stack加元素用push
            temp = temp.next;//Java ListNode没有->,用的是.
        }
        int size = stack.size();
        int[] arr = new int[size];
        for(int i = 0; i <size; i++){
   
   
            arr[i] = stack.pop().val;//stack没有top,pop可以同时取到值
        }
        return arr;
    }
}
  • 知识点总结

04 二维数组中的查找

难度 重点度 知识点 掌握度 链接
中等 已掌握
  • 题目描述:
    在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
  • 示例
[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
  • 解答
class Solution {
   
   
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
   
   
        if(matrix == null || matrix.length ==0 || matrix[0].length == 0) return false;
        int i = matrix[0].length-1, j = 0;
        while(i >= 0 && j < matrix.length){
   
   
            if(matrix[j][i] == target) return true;
            else if(matrix[j][i] > target) i--;
            else j++;
        }
        return false;
    }
}
  • 知识点总结

20 表示数值的字符串

难度 重点度 知识点 掌握度 链接
中等 here
  • 题目描述:
  • 示例
  • 解答
class Solution {
   
   
    public boolean isNumber(String s) {
   
   
        boolean hasDot = false, hasE = false, hasSign = false, hasNum = false;
        s = s.trim();
        for(int i = 0; i < s.length(); i++){
   
   
            char c = s.charAt(i);
            if(c == '+' || c == '-'){
   
   
                if(hasDot || hasNum || hasSign) return false;
                hasSign = true;
            }
            else if(c == 'e' || c == 'E'){
   
   
                if(!hasNum || hasE) return false;
                hasE = true;
                hasSign = false;
                hasNum = false;
                hasDot = false;//消除之前的.对e后面+-号的影响
            }
            else if(c == '.'){
   
   
                if(hasE || hasDot) return false;
                hasDot = true;
            }
            else if(c >= '0' && c <= '9'){
   
   
                hasNum = true;
            }
            else{
   
   
                return false;
            }
        }
        if(!hasNum) return false;
        return true;
    }
}
  • 知识点总结

48 最长不含重复字符的子字符串

难度 重点度 知识点 掌握度 链接
中等 A 已掌握 here
  • 题目描述:
    请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
  • 示例
输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
  • 解答
//最快
//index存储的key是该位置元素最近一次出现的位置
class Solution {
   
   
    public int lengthOfLongestSubstring(String s) {
   
   
        int n = s.length(), pre = 0, max = 0;
        int[] index = new int[128];
        Arrays.fill(index,-1);
        for(int i = 0; i < n; i++){
   
   
            if(index[s.charAt(i)] >= pre){
   
   `在这里插入代码片`
                pre = index[s.charAt(i)]+1;
            }
            index[s.charAt(i)] = i;
            max = Math.max(i-pre+1, max);
        }
        return max;
    }
}
  • 知识点总结

40 最小的k个数

难度 重点度 知识点 掌握度 链接
简单 快速排序、堆
  • 题目描述:
    输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
  • 示例
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
  • 解答
//时间快
//快速排序
class Solution {
   
   
    public int[] getLeastNumbers(int[] arr, int k) {
   
   
        int n = arr.length;
        if(n==k) return arr;
        if(n < k || k <= 0 || n==0) return new int[0];
        int l = 0, r = n-1;
        int index = partition(arr, l, r);
        while(index != k-1){
   
   
            if(index > k-1) r = index - 1;
            else l = index + 1;
            index = partition(arr, l, r);
        }
        return Arrays.copyOfRange(arr,0,k);//注意一:返回数组的一部分
    }

    private int partition(int[] arr, int l, int r){
   
   
        int mid = l + (r-l)/2;
        if(arr[l] > arr[r]) swap(arr, l, r);
        if(arr[mid] > arr[r]) swap(arr, mid, r);
        if(arr[mid] > arr[l]) swap(arr, l, mid);
        int key = arr[l];//注意二:把中间大小的数作为key,且在队头
        while(l < r){
   
   
            while(l < r && arr[r] >= key) r--;//注意三:这里有=
            arr[l] = arr[r];
            while(l < r && arr[l] <= key) l++;
            arr[r] = arr[l];
        }
        arr[l] = key;
        return l;
    }

    private void swap(int[] arr, int a, int b){
   
   
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}

//堆的时间复杂度较高,多次排序
//JAVA也有最大堆,最小堆(队头在最前面,因为队列只能访问队头,所以找到最小数中的最大数,就要把最大数放在队头,即最大堆)
//最小堆PriorityQueue<Integer> queue = new PriorityQueue<Integer>(),从小到大排序
//最大堆PriorityQueue<Integer> queue = new PriorityQueue<Integer>((a,b)->b-a)//默认是小于零,a<b,反过来就是b-a<0,从大到小排序
class Solution{
   
   
    public int[] getLeastNumbers(int[] arr, int k) {
   
   
        int n = arr.length;
        if(n==k) return arr;
        if(n < k || k <= 0 || n==0) return new int[0];
        int[] res = new int[k];
        PriorityQueue<Integer> queue = new PriorityQueue<
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值