剑指offer 21-36

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

在这里插入图片描述

class Solution {
    public int[] exchange(int[] nums) {
//判断奇数偶数用位运算 x&1=1奇数 x&1=0偶数
//调整顺序用首尾双指针法,左半边所有偶数与右半边所有奇数互换
        if(nums==null||nums.length==0||nums.length==1) return nums;
        int n=nums.length;
        int left=0;
        int right=n-1;
        while(left<right){
            while(left < right && nums[left]%2 !=0)  left++;
            while(left < right && nums[right]%2 ==0) right--;
            if(left<right){
                int temp=nums[left];
                nums[left]=nums[right];
                nums[right]=temp;
            }
        }
        return nums;
    }
}

22 链表中倒数第k个节点

在这里插入图片描述

class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        //边界情况 
        if(head==null||k==0) return null;
        //快慢指针法
        ListNode p=head;
        ListNode q=head;
        //快指针比慢指针先走k步
        while(q!=null&&k>0){
            q=q.next;
            k--;
        }
        while(q!=null){
            p=p.next;
            q=q.next;
        }
        return p;
    }
}

23 链表中环的入口节点

24 反转链表

1.迭代

 //1.迭代
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode pre=null;
        ListNode cur=head;
        ListNode temp;
        while(cur!=null){
            temp=cur.next;
            cur.next=pre;

            pre=cur;
            cur=temp;
        }
        return pre;
    }
}

2.递归

//递归
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode temp=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return temp;
    }
}

25 合并两个排序的链表

在这里插入图片描述

 //递归
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null&&l2!=null) return l2;
        if(l2==null) return l1;

        if(l1.val>l2.val){
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }else {
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }
    }
}

26.树的子结构 (*多看看)

在这里插入图片描述

巧妙的递归

// 1.创建一个辅助函数判断两棵树是否相等
//2.递归遍历A树的每一个节点作为根结点和B树进行比较
class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if(B==null||A==null) return false;
        // 我们规定树的子结构必须是 B 树的结构和结点值完全与 A 相同
        // 如果B树和A树相同, 那么也是一种子结构
        // 我们可以分为三种情况判断
        // 1. A树与B树完全相等
        // 2. A的左子树与B树完全相等
        // 3. A的右子树与B树完全相等
        // 此时可以分为三个递归遍历, 因为 || 具有短路性质, 如果在某一步返回 true, 则不需要继续递归
        return dfs(A,B)||isSubStructure(A.left,B)||isSubStructure(A.right,B);
    }
    public boolean dfs(TreeNode A,TreeNode B){
        // 如果 B 树为空, 证明 A 树 包含 B 树
        // 如果 A 树为空, 但 B 树不为空, 证明 A 里面不包含 B
        if(B==null) return true;
        if(A==null) return false;
        // 如果两棵树都不为空, 那么需要比较三样东西
        // 1. A的根节点与B的根节点是否相同
        // 2. A的左子树与B的左子树是否相同
        // 3. A的右子树与B的右子树是否相同
        return A.val==B.val && dfs(A.left,B.left)  && dfs(A.right,B.right);
    }
}

可读性强的写法

public boolean isSubStructure(TreeNode A, TreeNode B) {
    if(A == null || B == null) return false;
    return findRoot(A, B);
}

private boolean findRoot(TreeNode A, TreeNode B){  //判断当前根结点一不一致
    if(B == null) return true;
    if(A == null) return false;
    if(A.val == B.val){  //如果当前根结点一致,往下判断是否一致
        if(isMatch(A.left, B.left) && isMatch(A.right, B.right)) return true;
        //如果下面的子树不一致,返回去接着找一致的根结点
    }
    return findRoot(A.left, B) || findRoot(A.right, B);
}

private boolean isMatch(TreeNode A, TreeNode B){
    if(B == null) return true;
    if(A == null) return false;
    if(A.val == B.val){
        return isMatch(A.left, B.left) && isMatch(A.right, B.right);
    }else{
        return false;
    }
}

27.二叉树的镜像

在这里插入图片描述

递归

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        return MyTree(root);
    }
    public TreeNode MyTree(TreeNode root){
        if(root==null) return root;
        TreeNode temp=MyTree(root.left);
        root.left=MyTree(root.right);
        root.right=temp;
        return root;
    }
}

28. 对称的二叉树

在这里插入图片描述

递归

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return helper(root.left,root.right);   
    }
    public boolean helper(TreeNode root1,TreeNode root2){
        if(root1==null&&root2==null) return true;
        if(root1==null&&root2!=null) return false;
        if(root1!=null&&root2==null) return false;
        return root1.val==root2.val && helper(root1.left,root2.right) && helper(root1.right,root2.left);
    }
}
  
周赛看错的题目
class Solution {
    public String largestMerge(String word1, String word2) {
        int l1=word1.length();
        int l2=word2.length();
        StringBuilder merge=new StringBuilder();
       Map<Character,Integer> map=new TreeMap<>(
				new Comparator<Character>(){
        			@Override
        			public int compare(Character o1, Character o2) {
        				//利用Comparator来实现降序;
        				return (int) (o2-o1);
        			}
           });
        for(int i=0;i<l1;i++){
            map.put(word1.charAt(i),map.getOrDefault(word1.charAt(i),0)+1);
        }
        for(int i=0;i<l2;i++){
            map.put(word2.charAt(i),map.getOrDefault(word2.charAt(i),0)+1);
        }
        //使用Iterator来取key-value对;
		Set<Character> keySet = map.keySet();
	    Iterator<Character> iter = keySet.iterator();
	    while (iter.hasNext()) {
	        Character key = iter.next();
            int count=map.get(key);
	        while(count>0){
                merge.append(key);
                count--;
            }
	        }
        return merge.toString();
    }
    
}

29.顺时针打印矩阵

在这里插入图片描述

  • 空值处理: 当 matrix 为空时,直接返回空列表 [] 即可。
  • 初始化: 矩阵 左、右、上、下 四个边界 l , r , t , b ,用于打印的结果列表 res 。
  • 循环打印: “从左向右、从上向下、从右向左、从下向上” 四个方向循环,每个方向打印中做以下三件事 (各方向的具体信息见下表) ;
    • 根据边界打印,即将元素按顺序添加至列表 res 尾部;
    • 边界向内收缩 1 (代表已被打印);
    • 判断是否打印完毕(边界是否相遇),若打印完毕则跳出。
    • 返回值: 返回 res 即可。

在这里插入图片描述

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix==null||matrix.length==0) return new int[0];
        int m=matrix.length;
        int n=matrix[0].length;
        int[] res=new int[m*n];
        int l=0,r=n-1,t=0,b=m-1,x=0;
        while(true){
            //left-->right
           for(int i=l;i<=r;i++) res[x++] = matrix[t][i];
            if(++t > b) break;
            //top-->bottom
            for(int i=t;i<=b;i++) res[x++]=matrix[i][r];
            if(--r<l) break;
            //right-->left
            for(int i=r;i>=l;i--) res[x++]=matrix[b][i];
            if(--b<t) break;
            //bottom-->top
            for(int i=b;i>=t;i--) res[x++]=matrix[i][l];
            if(++l>r) break;
        }
        return res;
    }
}

30.包含min函数的栈

在这里插入图片描述

思路:辅助栈

在这里插入图片描述
在这里插入图片描述

代码实现

class MinStack {
Stack<Integer> A;
Stack<Integer> B;
    /** initialize your data structure here. */
    public MinStack() {
        A=new Stack<>();
        B=new Stack<>();
    }
    
    public void push(int x) {
        A.push(x);
        if(B.empty() || B.peek() >= x)
            B.push(x);
    }
    
    public void pop() {
         if(A.pop().equals(B.peek()))
            B.pop();
    }
    
    public int top() {
        return A.peek();
    }
    
    public int min() {
        return B.peek();
    }
}

31栈的压入 弹出序列

在这里插入图片描述

判断合不合法,用个栈试一试:

  • 把压栈的元素按顺序压入.
  • 当栈顶元素和出栈的第一个元素相同,则将该元素弹出,出栈列表指针后移并继续判断。
  • 最后判断出栈是否为空。
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Deque<Integer> stack=new ArrayDeque();
        int j=0;
        for(int num:pushed){
            stack.push(num);
            while(j<popped.length&&!stack.isEmpty()&&stack.peek()==popped[j]){
                stack.pop();
                j++;
            }  
        }
        return stack.isEmpty();
    }
}

32-1从上到下打印二叉树

在这里插入图片描述

层序遍历 注意用了jdk8的stream()

class Solution {
    public int[] levelOrder(TreeNode root) {
        if(root==null) return new int[0];
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        List<Integer> list=new ArrayList<Integer>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node=queue.poll();
            list.add(node.val);
            if(node.left!=null) queue.add(node.left);
            if(node.right!=null) queue.add(node.right);
        }
        //将Integer类型list复制为int数组 使用了java8的stream新特性  也可以直接写循环复制
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

32-2从上到下打印二叉树(数组)

在这里插入图片描述

比较传统的BFS

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //比较传统的BFS,在每一层将结果添加到集合中,并且清空集合
        List<List<Integer>> res=new ArrayList<>();
        if(root==null) return res;
        List<Integer> list=new ArrayList<>();
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int n=queue.size();
            for(int i=0;i<n;i++){
            TreeNode node=queue.poll();
            list.add(node.val);
            if(node.left!=null) queue.offer(node.left);
            if(node.right!=null) queue.offer(node.right);
            }
            res.add(new ArrayList<>(list));
            list.clear();
        }
        return res;
    }
}

32-3 从上到下打印二叉树(交替顺序 数组)

在这里插入图片描述

层序遍历 + 双端队列

  • 利用双端队列的两端皆可添加元素的特性,设打印列表(双端队列) list,并规定:

    1. 奇数层 则添加至 list 尾部 ,
    2. 偶数层 则添加至 list 头部 。
  • 算法流程:
    - 特例处理: 当树的根节点为空,则直接返回空列表 [] ;
    - 初始化: 打印结果空列表 res ,包含根节点的双端队列 deque ;
    - BFS 循环: 当 deque 为空时跳出;
    - 新建列表 list ,用于临时存储当前层打印结果;
    - 当前层打印循环: 循环次数为当前层节点数(即 deque 长度);
    - 出队: 队首元素出队,记为 node;
    - 打印: 若为奇数层,将 node.val 添加至 list 尾部;否则,添加至 list 头部;
    - 添加子节点: 若 node 的左(右)子节点不为空,则加入 deque ; 将当前层结果 list 添加入 res ;
    - 返回值: 返回打印结果列表 res 即可;
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res=new ArrayList<>();
        if(root==null) return res;
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int n=queue.size();
            //LinkedList实现双端队列
             LinkedList<Integer> list=new LinkedList<>();
            for(int i=0;i<n;i++){
                TreeNode node=queue.poll();
                //用res的大小判断已经放入多少list,从而判断奇偶层
                //用双端队列前后两端放置实现交替
                if(res.size() % 2 == 0) {list.addLast(node.val); }else list.addFirst(node.val);
                if(node.left!=null)  queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);
            }
           res.add(list);
        }
        return res;
    }
}

33.二叉搜索树的后序遍历

在这里插入图片描述

法一: 递归分治

在这里插入图片描述

class Solution {
    public boolean verifyPostorder(int[] postorder) {
       
        return  recur(postorder,0,postorder.length-1);
    }
    public boolean recur(int[] postorder,int i,int j){
        //递归出口
        if(i>=j) return true;
        //找左右子树并标记
        int root=postorder[j];
        int p=i;
        while(postorder[p]<root) p++;
        int m=p;//标记左右子树分界点
        while(postorder[p]>root) p++;//遍历右子树,检查是否符合要求
        return p==j && recur(postorder,i,m-1) && recur(postorder,m,j-1);
    }
}

在这里插入图片描述

法二:单调栈

后序遍历倒序: [ 根节点 | 右子树 | 左子树 ] 。
类似 先序遍历的镜像 ,即先序遍历为 “根、左、右” 的顺序,
而后序遍历的倒序为“根、右、左” 顺序。

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        Stack<Integer> stack = new Stack<>();
        int root = Integer.MAX_VALUE;
        for(int i = postorder.length - 1; i >= 0; i--) {
            if(postorder[i] > root) return false;
            while(!stack.isEmpty() && stack.peek() > postorder[i])
            	root = stack.pop();
            stack.add(postorder[i]);
        }
        return true;
    }
}

题解详情

34.二叉树中和为某一值的路径

在这里插入图片描述

思路:

本问题是典型的二叉树方案搜索问题,使用回溯法解决,其包含 先序遍历 + 路径记录 两部分。

  • 先序遍历: 按照 “根、左、右” 的顺序,遍历树的所有节点。
  • 路径记录: 在先序遍历中,记录从根节点到当前节点的路径。当路径为 ① 根节点到 叶节点 形成的路径② 各节点值的和等于目标值 sum 时,将此路径加入结果列表。
class Solution {
    LinkedList<List<Integer>> res=new LinkedList<>();
    LinkedList<Integer> path=new LinkedList<>();  //注意前后都要是 LinkedList
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        findSum(root,sum);
        return res;
    }
    public void findSum(TreeNode root,int target){
        if(root==null) return; //说明到了叶子节点

        path.add(root.val);
        target=target-root.val;
        if(target==0 && root.left==null && root.right==null){
            res.add(new LinkedList(path));  //注意这里要new一个 LinkedList 把path放进去
        }

        //递归
        findSum(root.left,target);
        findSum(root.right,target);

         path.removeLast(); //回溯

    }
}

35.复制链表的复制

在这里插入图片描述

代码细节

注意细节 cur不为空时copyNode.next不一定不为空
while(cur!=null&&cur.random!=null)不对 注意逻辑细节

class Solution {
    public Node copyRandomList(Node head) {
        if(head==null) return head;
        //复制已有节点
        Node cur=head;
        while(cur!=null){
            Node copyNode=new Node(cur.val);
            copyNode.next=cur.next;
            cur.next=copyNode;
            cur=cur.next.next;
        }
        //复制随机指针
        cur=head;
        //while(cur!=null&&cur.random!=null)不对 注意逻辑细节
        while(cur!=null){
            if(cur.random!=null)  {
                cur.next.random=cur.random.next;
            }
            cur=cur.next.next;
        }
        //拆分链表 注意细节 cur不为空时copyNode.next不一定不为空
        Node copyHead=head.next;
        cur=head;
        while(cur!=null){
            Node copyNode=cur.next;
            cur.next=cur.next.next;
            cur=cur.next;
            if(copyNode.next!=null){
                copyNode.next=copyNode.next.next;
                copyNode=copyNode.next;
            }
        }
        return copyHead;
    }
}

36.二叉搜索树与双向链表

性质:二叉搜索树的中序遍历为 递增序列

在这里插入图片描述
在这里插入图片描述

class Solution {
    Node head;
    Node pre;
    public Node treeToDoublyList(Node root) {
        if(root==null) return root;
        dfs(root);
        //循环:头head  尾pre  相连
        head.left=pre;
        pre.right=head;
        return head;
    }
    public void dfs(Node cur){
        if(cur==null) return;//递归出口,遍历结束
        dfs(cur.left);//中序遍历——左 中 右
        //中:递归操作主代码体
        if(pre==null) head=cur;  // 头节点
        else pre.right=cur;
        cur.left=pre;
        //指针移动
        pre=cur;

        dfs(cur.right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值