剑指offer

1. 前言

       打算刷一遍《剑指Offer》中的题,其中部分解法来自于原书,建议可以观看原书,相关分析很有益处,不要为了刷题而刷题。

2. 数组中重复的数字

2.1 找出数组中重复的数字

/**
 *
 * 在一个长度为 n 的数组里的所有数字都在 0~n-1 的范围内。数组中某
 * 些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了
 * 几次。请找出数组中任意一个重复的数字。
 * 例如,如果输入长度为7的数组{2,3, 1,0,2,5, 3},那么对应的输出是重复的数字2或者3。
 *
 * @author wangzhao
 * @date 2020/6/16 21:28
 */
public class RepeatNumOfArray {

    /**
     * 解法一:
     *      算法分析:使用 set 或者 map
     *      效率分析:
     *                时间复杂度,O(N)
     *                空间复杂度,O(N)
     */
    public static int getRepeatNum(int[] array){
        // 代码简单,省略
        return -1;
    }

    /**
     * 解法二:
     *      算法分析:数组长度为 n 并且数组元素的范围都在 0~n-1,倘若没有重复数字,我们对数组进行排序后,元素的值等于其下标。
     *                现在,我们从头到尾开始遍历,将每个元素放到其对应的数组下标处,
     *                如果当前遍历的下标与当前被遍历的元素相等,则说明其已经出现在正确的位置,
     *                否则如果该下标已经有了与下标相同的值,则说明出现了重复元素。
     *      效率分析:
     *                  时间复杂度,O(N)
     *                  空间复杂度,O(1)
     */
    public static int getRepeatNum_2(int[] array){
        int repeatNum = -1;
        if(array == null){
            return repeatNum;
        }

        for(int i=0; i < array.length; i++){
            // 此时,元素在正确的位置
            if (array[i] == i){
                continue;
            }
            else if (array[i] == array[array[i]]){
                repeatNum = array[i];
                break;
            }else{
                swap(array, i, array[i]);
                // 这里不要忘了,保持下标不动,交换来的元素还没有进行判断,不可以跳过
                i--;
            }
        }
        return repeatNum;
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

2.2 不修改数组找出重复的数字

/**
 *
 * 在一个长度为 n+1 的数组里的所有数字都在 1~n 的范围内,所以数组
 * 中至少有一个数字是重复的。
 *
 * 请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},那
 * 么对应的输出是重复的数字2或者3。
 *
 * @author wangzhao
 * @date 2020/6/16 22:11
 */
public class RepeatNumOfArray_II {


    /**
     * 解法一:
     *      算法分析:使用 set 或者 map
     *      效率分析:
     *                时间复杂度,O(N)
     *                空间复杂度,O(N)
     */
    public static int getRepeatNum(int[] array){
        // 代码简单,省略
        return -1;
    }

    /**
     * 解法一:
     *      算法分析:我们将数组的值从中间数字 m 划分,如果整个数组中 1~m 之间元素的个数超过了 m,则这个重复数字出现在 1~m 之间,
     *                否则出现在 m+1~n 之间。以从,通过二分的方法不断缩小范围,最终可以确定重复数字
     *      效率分析:
     *                时间复杂度,O(NlogN)
     *                空间复杂度,O(1)
     */
    public static int getRepeatNum_2(int[] array){
        int repeatNum = -1;
        if (array == null){
            return repeatNum;
        }

        int left = 1;
        int right = array.length - 1;

        while (left <= right){
            int mid = (left + right) >> 1;
            int count = getNumCount(array, left, mid);
            // 如果 count 的个数超过了 left ~ mid 之间的个数,则重复数字出现在 left ~ mid 之间
            // 如何判断 count 有没有超过 left ~ mid 之间的数字?
            // 加入 left = 1, mid = 2, 那么两者之间应该存在两个数,即 mid - left + 1

            if (left == right){
                repeatNum = mid;
                break;
            }
            // 此时重复数字出现在了 left ~ mid 之间
            if (count > mid - left + 1){
                right = mid;
            }else{
                left = mid + 1;
            }
        }
        return repeatNum;
    }

    /**
     *   获得 left 到 mid 之间的数字个数
     */
    private static int getNumCount(int[] array, int left, int mid) {
        int count = 0;
        for (int num : array){
            if(num >= left && num <= mid){
                count++;
            }
        }
        return count;
    }
}

3. 二维数组查找

/**
 *
 * 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,
 * 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的
 * 个二维数组和一个整数,判断数组中是否含有该整数。
 *
 *
 * @author wangzhao
 * @date 2020/6/16 22:36
 */
public class SearchInTwoDimensionalArray {


    /**
     *  算法分析:
     *          选择右上角的元素,和目标值比较。
     *          如果等于,则找到。
     *          如果小于,则说明该列所有的元素都大于目标值,移动到其左边的元素。
     *          如果大于,则说明该行所有的元素都小于目标值,移动到其下边的元素。
     *
     *          这样,每次可以不断缩小一行或者一列,数组范围不断缩小,最终被确定。
     *
     *   效率分析:
     *          时间复杂度:O(n + m)
     *          空间复杂度:O(1)
     */
    public static boolean find(int[][] array, int target){
        boolean flag = false;
        if (array == null){
            return flag;
        }

        int rows = array.length;
        int cols = array[0].length;

        // 取右上角的元素
        for (int i = 0, j = cols - 1; i < rows && j >= 0;){
            if (array[i][j] == target){
                flag = true;
                break;
            }
            else if(array[i][j] < target){
                i++;
            }else{
                j--;
            }
        }
        return flag;
    }
}

4. 倒序打印列表

import java.util.Stack;

import	java.util.Stack;
/**
 *
 * 题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。
 * @author wangzhao
 * @date 2020/6/16 23:10
 */

class ListNode{
    int value;
    ListNode next;
}

public class PrintListInReverseOrder {

    /**
     *  算法分析:逆序,则可以使用栈来实现逆序
     *  
     *  效率分析:
     *          时间复杂度:O(N)
     *          空间复杂度:O(N)
     */
    public static void printList(ListNode head){
        if(head == null){
            return;
        }
        Stack<Integer> stack = new Stack<Integer> ();
        ListNode pointer = head;
        while (pointer != null){
            stack.push(pointer.value);
            pointer = pointer.next;
        }
        while (!stack.isEmpty()){
            System.out.println(stack.pop());
        }
    }

    /**
     *  算法分析:使用递归,可以代替栈 
     *  
     *  效率率分析:
     *             时间复杂度:O(N)
     *             空间复杂度:O(1)
     */
    public static void printList2(ListNode head){
        if (head == null){
            return;
        }
        printList(head.next);
        System.out.println(head.value);
    }

}

5. 重建二叉树


/**
 * @author wangzhao
 * @date 2020/6/16 23:24
 */

class TreeNode {
    int value;
    TreeNode  left;
    TreeNode  right;

    public TreeNode(int value){
        this.value = value;
    }

}

public class RebuildBinaryTree {

    public static TreeNode reConstructBinaryTree(int[] preOrder, int[] inOrder){
        TreeNode root = null;
        root = rebuildTree(preOrder, 0, preOrder.length-1, inOrder, 0 , inOrder.length - 1);
        return root;
    }

    private static TreeNode rebuildTree(int[] preOrder, int preStart, int preEnd, int[] inOrder, int inStart, int inEnd) {
        if (preStart > preEnd || inStart > inEnd)
            return null;
        // 根节点
        TreeNode root = new TreeNode(preOrder[preStart]);
        // 寻找根节点在中序序列的位置
        for (int i = inStart; i <= inEnd; i++) {
            if (inOrder[i] == preOrder[preStart]) {
                // 可以计算出中序序列的左右子树序列为:左:inStart~i -1,右:i+1~inEnd。
                // 前序序列的左右子树:
                // 左:preStart+1~preStart+i-inStart,
                // 右:preStart+i-inStart+1~preEnd
                root.left = rebuildTree(preOrder, preStart + 1, preStart + i - inStart, inOrder, inStart, i - 1);
                root.right = rebuildTree(preOrder, preStart + i - inStart + 1, preEnd, inOrder, i + 1, inEnd);
            }
        }
        return root;
    }
}

6. 二叉树的下一个节点

/**
 *
 * 题目:给定一棵二叉树和其中的一个节点,如何找出中序遍历序列的
 * 下一个节点?树中的节点除了有两个分别指向左、右子节点的指针,
 * 还有一个指向父节点的指针。
 *
 * @author wangzhao
 * @date 2020/6/17 20:50
 */

class BinaryTree{
    int value;
    BinaryTree left;
    BinaryTree right;
    BinaryTree parent;
}

public class NextNodeOfBinaryTree {

    /**
     *  如果一个节点有右子树,那么其下一个节点是右子树的最左节点。
     *
     *  如果没有右子树,并且该节点是其父节点的左子树,那么其下一个节点使其父节点。
     *
     *  如果没有右子树,并且该节点使其父节点的右子树,那么需要沿着父节点向上遍历,直到该节点是其父节点的左节点。
     *
     */
    public static BinaryTree getNext(BinaryTree node){
        BinaryTree next = null;
        if (node == null){
            return next;
        }

        if (node.right != null){
            BinaryTree right = node.right;
            while (right.left != null){
                right = right.left;
            }
            next = right;
        }else if (node.parent != null){
            BinaryTree current = node;
            BinaryTree parent = node.parent;
            while (parent != null && parent.left != current){
                current = parent;
                parent = parent.parent;
            }
            next = parent;
        }
        return next;
    }
}

7. 两个栈实现一个队列

import java.util.Stack;

/**
 * 用两个栈实现一个队列。队列的声明如下,请实现它的两个函
 * 数 appendTail 和 deleteHead ,分别完成在队列尾部插入节点和在队列头部删
 * 除节点的功能。
 *
 * @author wangzhao
 * @date 2020/6/17 22:03
 */
public class ImplementQueueWithTwoStacks {

    private static Stack stackA = new Stack();
    private static Stack stackB = new Stack();

	// 画图较容易找到规律
    public static void appendTail(Object object){
        stackA.push(object);
    }

    public static  Object deleteHead(){
        if (stackB.isEmpty() && stackA.isEmpty()){
            return null;
        }
        if (stackB == null){
            while (!stackA.isEmpty()){
                stackB.push(stackA.pop());
            }
        }
        return stackB.pop();
    }

}

8. 两个队列实现一个栈

import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * 用两个队列实现一个栈。队列的声明如下,请实现它的两个函
 * 数 appendTop 和 deleteTop ,分别完成在栈顶插入节点和在栈顶删
 * 除节点的功能。
 *
 * @author wangzhao
 * @date 2020/6/17 22:03
 */
public class ImplementQueueWithTwoStacks {

    private static Queue queueA = new LinkedList();
    private static Queue queueB = new LinkedList();

    public static void appendTop(Object object){
        if (queueB.isEmpty()){
            queueA.offer(object);
        }else{
            queueB.offer(object);
        }
    }

    public static  Object deleteTop(){
        if (!queueA.isEmpty()) {
            while (queueA.size() > 1) {
                queueB.offer(queueA.poll());
            }
            return queueA.poll();
        }else{
            while (queueB.size() > 1){
                queueA.offer(queueB.poll());
            }
            return queueB.poll();
        }
    }
}

9. 斐波那契数列

/**
 *  斐波那契数列:求斐波那契数列的第 n 项
 *
 * 斐波那契数列格式为:1、1、2、3、5、8、13、21、34
 *
 * @author wangzhao
 * @date 2020/6/17 22:55
 */
public class Fibonacci {

    /**
     * 解法一:
     * 算法分析:通过递归
     *                  0, (n = 0)
     *          f(n) =  1, (n = 1)
     *                  f(n-2) + f(n-1), (n >= 2)
     * 效率分析:
     *          时间复杂度O(2^N)
     *          空间复杂度O(N)
     */
    public static int fibonacci1(int n){
        if (n <= 1){
            return n;
        }
        return fibonacci1(n-2) + fibonacci1(n-1);
    }



    /**
     * 解法二:
     * 算法分析:通过数组保存每一项的值
     *
     * 效率分析:
     *          时间复杂度O(N)
     *          空间复杂度O(N)
     */
    public static int fibonacci2(int n){

        if (n <= 0){
            return 0;
        }

        int[] array = new int[n];
        array[0] = 1;
        array[1] = 1;
        for (int i=2; i < n; i++){
            array[i] = array[i-1] + array[i-2];
        }
        return array[n-1];
    }

    /**
     * 解法三:
     * 算法分析:通过三个变量,保存当前值以及其前两项的值
     *
     * 效率分析:
     *          时间复杂度O(N)
     *          空间复杂度O(1)
     */
    public static int fibonacci3(int n){
        if (n <= 1){
            return n;
        }
        if (n == 2){
            return 1;
        }
        int a = 0;
        int b = 1;
        int sum = 1;
        for (int i = 3; i <= n; i++){
            a = b;
            b = sum;
            sum = a + b;
        }
        return sum;
    }
}

10. 青蛙跳台阶

/**
 * 青蛙跳台阶
 * @author wangzhao
 * @date 2020/6/17 23:19
 */
public class FrogJumpingStairs {

    /**
     *  假设有 n 阶台阶(n > 1),
     *  如果我们第一步选择跳一步,则此时数目为剩余 n-1 阶的跳法数目,f(n-1) 
     *  如果我们第一步选择跳两步,则此时数目为剩余 n-2 阶的跳法数目,f(n-2) 
     */
    public static int jump(int n){
        if (n <= 1){
            return n;
        }
        return jump(n-1) + jump(n-2);
    }

}

11. 旋转数组的最小数字

/**
 * 题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为
 * 数组的旋转。输入一个递增排序的数组的一-个旋转,输出旋转数组的最小
 * 元素。例如,数组{3,4,5, 1,2}为{1,2,3,4, 5}的一一个旋转,该数组的最小
 * 值为1。
 *
 * @author wangzhao
 * @date 2020/6/17 23:58
 */
public class RotateSmallestNumberOfArray {

    /**
     * 解法一:
     * 算法分析:从头到尾遍历,寻找最小的元素
     *
     * 效率分析:
     *          时间复杂度:O(N)
     *          空间复杂度:O(1)
     */
    public static int getRotateNumber1(int[] array){
        // 代码省略
        return 0;
    }

    /**
     * 解法二:
     * 算法分析:数组被旋转后,分别为两个有序数组。
     *           通过二分法,如果中间mid的值大于等于左边left的值,最说明最小的数字一定不会出现在left-mid之间,此时left移动到mid的位置。
     *           如果中间mid的值小于等于右边right的值,则说明最小的数字出现在mid的左边,所以可以去除mid-right之间的范围,此时right移动到mid的位置。
     *           left和right始终位于两个数组中,当left与right之间的差为1,则说明找到了目标值,此时最小值位于后面的数组,即right处
     *
     * 效率分析:
     *          时间复杂度:O(logN)
     *          空间复杂度:O(1)
     */
    public static int getRotateNumber2(int[] array){
        int num = 0;
        if (array == null){
            return num;
        }
        int left = 0;
        int right = array.length - 1;
        while (right - left > 1){
            int mid = (left + right) / 2;
            if (array[mid] >=  array[left]){
                left = mid;
            }else if(array[mid] <= array[right]){
                right = mid;
            }
        }
        return array[right];
    }
}

12. 矩阵中的路径

import java.util.Stack;

/**
 *
 * 题目:请设计一个函数,用来判断在一个矩阵中 是否存在一条包含某字符串所有字符的路径。
 * 路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,
 * 那么该路径不能再次进入该格子。
 *
 * 例如,在下面的3x4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用下画线标出)。
 * 但矩阵中不包含字符串“abfb"的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
 *
 *  a b t g
 *  c f c s
 *  j d e h
 *
 * @author wangzhao
 * @date 2020/6/19 0:16
 */
public class PathsInMatrix {


    /**
     *  算法分析:
     *        首先需要一个栈,如果当前节点等于目标子符时,则说明可以走,则将坐标入栈,
     *        如果其上下左右都不可以走,则弹栈。
     *        接着,因为走过的字符不能再走,所以需要一个数组记录每一次走过的路径。
     */
    public static boolean hasPath(char[][] matrix, String str){
        if (matrix == null || str == null) {
            return false;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;


        // xStack 用来存储横坐标
        Stack<Integer> xStack = new Stack<Integer>();
        // yStack 用来存储纵坐标
        Stack<Integer> yStack = new Stack<Integer>();
        // index 用来记录当前遍历到字符的下标
        int index = 0;
        // flag 用来记录对应的位置是否有走过
        int[][] flag = new int[rows][cols];
        int len = str.length();

        for (int x = 0; x < rows; x++){
            for (int y = 0; y < cols; y++){
                if (matrix[x][y] == str.charAt(index)){
                    flag[x][y] = 1;
                    xStack.push(x);
                    yStack.push(y);

                    while (!xStack.isEmpty()){
                        if (xStack.size() == len){
                            return true;
                        }
                        // 向右走
                        if (y + 1 < cols && flag[x][y+1] == 0 && matrix[x][y+1] == str.charAt(index + 1)){
                            index++;
                            flag[x][y+1] = 1;
                            xStack.push(x);
                            yStack.push(++y);
                        }
                        // 向下走
                        else if (x + 1 < rows && flag[x+1][y] == 0 && matrix[x+1][y] == str.charAt(index + 1)){
                            index++;
                            flag[x+1][y] = 1;
                            xStack.push(++x);
                            yStack.push(y);
                        }
                        // 向左走
                        else if (y - 1 >= 0 && flag[x][y-1] == 0 && matrix[x][y-1] == str.charAt(index + 1)){
                            index++;
                            xStack.push(x);
                            yStack.push(--y);
                            flag[x][y-1] = 1;
                        }
                        // 向上走
                        else if (x - 1 >= 0 && flag[x-1][y] == 0 && matrix[x-1][y] == str.charAt(index + 1)){
                            index++;
                            flag[x-1][y] = 1;
                            xStack.push(--x);
                            yStack.push(y);
                        }else{
                            // 此时,说明上下左右都不相同,需要弹栈
                            x = xStack.pop();
                            y = yStack.pop();
                        }
                    }
                }
                index = 0;
                flag = new int[rows][cols];
            }
        }
        return false;
    }

    public static void main(String[] args) {
        char[][] matrix = {
                {'a', 'b', 't', 'g'},
                {'c', 'f', 'c', 's'},
                {'j', 'd', 'e', 'h'}
            };
        boolean result = hasPath(matrix, "abfb");
        System.out.println(result);
    }

}

13. 机器人的运动范围

/**
 *
 * 题目:地上有一个 m 行 n 列的方格。
 * 一个机器人从坐标(0, 0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列
 * 坐标的数位之和大于k的格子。
 *
 * 例如,当k为18时,机器人能够进入方格(35, 37),因为3+5+3+7=18。
 * 但它不能进入方格(35, 38),因为3+5+3+8=19。请问该机器人能够到达多少个格子?
 *
 * @author wangzhao
 * @date 2020/6/19 1:24
 */
public class RobotRangeOfMotion {

    private static int[][] flag;

    /**
     * 该题与上一题非常类似,所以可以通过栈来实现。
     * 
     * 这里选择递归的方式实现,每一个点都有四种走法。所以总的格子为当前的格子 + 四个点的格子
     */
    public static int movingCount(int threshold, int rows, int cols){

        if (threshold < 0 || rows < 0 || cols < 0){
            return 0;
        }

        flag = new int[rows][cols];

        return movingCountCore(0, 0, rows, cols, threshold);
    }

    public static int movingCountCore(int row, int col, int rows, int cols, int threshold){
        if (row >= rows || col >= cols || row < 0 || col < 0 || !canMoving(row, col, threshold) || flag[row][col] == 1){
            return 0;
        }
        flag[row][col] = 1;
        // 此时,该点可以走,所以个数 + 1
        int count = 1;
        count += movingCountCore(row, col + 1, rows, cols, threshold) +
                 movingCountCore(row + 1, col, rows, cols, threshold) +
                 movingCountCore(row, col - 1, rows, cols, threshold) +
                movingCountCore(row - 1, col, rows, cols, threshold);
        return count;
    }


    public static boolean canMoving(int row, int col, int threshold){
        // 计算横纵坐标每位数字之和
        int sum = 0;
        while (row > 0 || col > 0){
            sum += row % 10;
            sum += col % 10;
            row /= 10;
            col /= 10;
        }

        if (sum > threshold){
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int count = movingCount(5, 5, 5);
        System.out.println(count);
    }


}

14. 剪绳子

/**
 * @author wangzhao
 * @date 2020/6/20 0:20
 */
public class CutRope {


    /**
     *  动态规划:
     *      假设绳子长度为 n,f(n)为长度为n段绳子被剪成若干段后的最大乘积。
     *
     *      如果我们在长度为 i 的地方对绳子进行,则是长度为 i 的绳子的乘积为 f(i),
     *      剩下绳子的长度则为 n-i,该段绳子的乘积为f(n-i)
     *
     *      所以,f(n) = max(f(i) * f(n-i))
     */
    public static int maxProductAfterCutting1(int n){

        if (n < 2){
            return 0;
        }
        if (n < 4){
            return n - 1;
        }
        int[] array = new int[n+1];
        array[1] = 1;
        array[2] = 2;
        array[3] = 3;

        for (int i = 4; i <= n; i++){
            int max = 0;
            for (int j = 1; j <= i / 2; j++){
                if (array[j] * array[i-j] > max){
                    max = array[j] * array[i-j];
                }
            }
            array[i] = max;
        }
        return array[n];
    }

    /**
     * 如果绳子长度>=5,将绳子尽可能分成长度为3的,剩下的则是长度为2的,此时乘积最大。
     */
    public static int maxProductAfterCutting2(int n){
        if (n < 2){
            return 0;
        }
        if (n < 4){
            return n-1;
        }
        int num = 1;
        while (n - 3>= 2){
            num *= 3;
            n -= 3;
        }
        num *= n;
        return num;
    }

    public static void main(String[] args) {
        int maxVal = maxProductAfterCutting2(6);
        System.out.println(maxVal);

    }

}

16. 删除链表中的节点

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.util.List;

/**
 *
 * 题目一:在0(1)时间内删除链表节点。
 * 给定单向链表的头指针和一个节点指针,定义一个函数在0(1)时间内删除该节点。
 *
 * @author wangzhao
 * @date 2020/7/1 22:09
 */


public class DeleteNodeOfTheLinkedList {

    /**
     * 删除链表中的一个节点时,我们通常的做法是选择先定位到被删除节点q的前驱节点p,然后令p.next = q.next即可。
     * 但是这样做的时间复杂度是O(n),所以我们跳过该解法。
     *
     * 如果被删除的节点不是尾节点,假设被删除节点为q,其后继节点为p,那么只要用p的值替换q的值,然后令q.next = p.next 即可。
     * 如果被删除的节点是尾节点,需要遍历整个链表知道到尾节点的前驱q,直接令q.next = null 即可。
     *
     * 时间复杂度为 ((n-1)O(1) + O(n) / n) = O(1)
     */
    public static ListNode deleteNode(ListNode head, ListNode node){
        if (head == null || node == null){
            return null;
        }

        // 被删除的节点为头节点
        if (head == node){
            head = node.next;
            return head;
        }

        // 获取当前节点的后继节点
        ListNode successorNode = node.next;
        if (successorNode == null){
            // 如果被删除的节点是链表最后一个节点
            ListNode tempNode = head;
            while (tempNode.next != node){
                tempNode = tempNode.next;
            }
            tempNode.next = null;
        }else{
            node.value = successorNode.value;
            node.next = successorNode.next;
        }
        return head;
    }
}

17. 删除链表中重复的节点

/**
 *
 * 题目二:删除链表中重复的节点。在一个排序的链表中,如何删除重复的节点?
 *
 * @author wangzhao
 * @date 2020/7/1 22:40
 */
public class DeleteDuplicateNodesInTheLinkedList {
    public static ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null){
            return null;
        }

        // 添加一个头节点,这样就不用分别讨论原链表中首元素是否出现在头部。
        ListNode head = new ListNode(0);
        head.next = pHead;

		// 需要三个指针
        ListNode p = head;
        // q1 指针是 p 后面的第一个节点
        ListNode q1 = pHead;
        // q2 指针用来记录是否和q1的值相等
        ListNode q2 = q1.next;

        while (q2 != null){
            if (q1.value == q2.value){
                // 一直循环,跳过重复的节点
                while (q2 != null && q1.value == q2.value){
                    q2 = q2.next;
                }
                p.next = q2;
            }else{
                p = q1;
            }
            q1 = q2;
            if (q1 != null){
                q2 = q1.next;
            }
        }
        // 跳过被手动添加的头节点
        return head.next;
    }
}

未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值