leetcode剑指Offer2

剑指 Offer 28. 对称的二叉树

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return recu(root.left,root.right);
    }
    public boolean recu(TreeNode left,TreeNode right){
        if(left==null&&right==null) return true;
        if(left==null||right==null||left.val!=right.val)return false;
        return recu(left.left,right.right)&&recu(left.right,right.left);
    }

剑指 Offer 29. 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null||matrix.length==0) return new int[0];
        int row = matrix.length, col = matrix[0].length;
        int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        boolean[][] flag=new boolean[row][col];
        int directionIndex = 0;//顺时针打印需要顺序,通过下标保证顺时针循环
        int m = 0, n = 0;
        int total = row * col;//表示数组的总长度,以此作为循环结束条件
        int[] res=new int[total];
        for (int i = 0; i < total; i++) {
            res[i]=matrix[m][n];
            flag[m][n]=true;
            int nextRow=m+direction[directionIndex][0];int nextCol=n+direction[directionIndex][1];
            if(nextRow<0||nextRow>=row||nextCol<0||nextCol>=col||flag[nextRow][nextCol])
            {
                directionIndex=(directionIndex+1)%4;//保证顺时针转的方向
            }
            m+=direction[directionIndex][0];
            n+=direction[directionIndex][1];
        }
        return res;
    }
}

剑指 Offer 30. 包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.

提示:

各函数的调用总次数不超过 20000 次

class MinStack {
    Stack<Integer> a,b;
    /** initialize your data structure here. */
    public MinStack() {
        a=new Stack<>();
        b=new Stack<>();
    }

    public void push(int x) {
        a.push(x);
        if(b.isEmpty()||b.peek()>=x){
            b.push(x);
        }
    }

    public void pop() {
        int temp=a.pop();
        if(temp==b.peek())
        {
            b.pop();
        }
    }

    public int top() {
        return a.peek();
    }

    public int min() {
        return b.peek();
    }
}

b栈作为辅助栈,用来存储a栈中的非降序数据。a栈存储所有正常数据。

剑指 Offer 31. 栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。

示例 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:

输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。

    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack=new Stack<>();
        int j=0;//记录popped下标
        for(int num:pushed)
        {
            stack.push(num);
            while(!stack.isEmpty()&&stack.peek()==popped[j]){
                stack.pop();
                j++;
            }
        }
        return stack.isEmpty();
        
    }

剑指 Offer 32 - II. 从上到下打印二叉树 II

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> node = new LinkedList<>();
        List<List<Integer>> res = new LinkedList<>();
        if(root!=null)
            node.add(root);
        while (!node.isEmpty()) {
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = node.size(); i > 0; i--) {
                TreeNode tmp = node.poll();
                list.add(tmp.val);
                if(tmp.left!=null)node.add(tmp.left);
                if(tmp.right!=null)node.add(tmp.right);
                
            }
            res.add(list);
        }
        return res;
    }

剑指 Offer 32 - III. 从上到下打印二叉树 III

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> node = new LinkedList<>();
        List<List<Integer>> res = new LinkedList<>();
        if(root!=null) node.add(root);
        while (!node.isEmpty()) {
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = node.size(); i > 0; i--) {
                TreeNode tmp = node.poll();
                //使用res.size作为奇偶判定,如果是奇数则依次放在双向列表前端
                if(res.size()%2==0){
                    list.addLast(tmp.val);
                }
                else list.addFirst(tmp.val);
                if(tmp.left!=null)node.add(tmp.left);
                if(tmp.right!=null)node.add(tmp.right);
            }
            res.add(list);
        }
        return res;
    }
}

剑指 Offer 33. 二叉搜索树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

   public boolean verifyPostorder(int[] postorder) {
        return recur(postorder,0,postorder.length-1);
    }
    //postorder表示一直要使用的数组,i,j表示所要递归子树的起止坐标
    public boolean recur(int[] postorder,int i,int j)
    {
        if(i>=j)return true;
        int p=i;
        while(postorder[p]<postorder[j])p++;
        //m存储找到的左子树临界坐标
        int m=p;
        //判断是否满足二叉搜索树的条件,左子树节点都小于根节点,右子树节点都大于根节点。即判断最后p==j.
        while(postorder[p]>postorder[j])p++;
        return p==j&&recur(postorder,i,m-1)&&recur(postorder,m,j-1);
    }

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

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

class Solution {
    public LinkedList<Integer> path=new LinkedList<>();
    public List<List<Integer>> res=new LinkedList<>();
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        dfs(root,target);
        return res;
    }
    public void dfs(TreeNode root,int tar)
    {
        if(root==null)return;
        int val=root.val;
        tar-=val;
        path.add(val);
        if(tar==0&&root.left==null&&root.right==null)
            res.add(new LinkedList<>(path));
        dfs(root.left,tar);
        dfs(root.right,tar);
        path.removeLast();
    }
}

剑指 Offer 35. 复杂链表的复制

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

本题要求我们对一个特殊的链表进行深拷贝
利用哈希表的查询特点,考虑构建 原链表节点 和 新链表对应节点 的键值对映射关系,再遍历构建新链表各节点的 next 和 random
引用指向即可。

    public Node copyRandomList(Node head) {
        if(head==null)return null;
        //保存Node头节点,以便后续使用
        Node cur=head;
        //使用HashMap完成复制
        HashMap<Node,Node> map=new HashMap<>();
        while(cur!=null){
            map.put(cur,new Node(cur.val));
            cur=cur.next;
        }
        //重置cur节点到头部
        cur=head;
        //通过HashMap的键值映射完成复制
        while(cur!=null){
            //map.get映射的是新复制出的节点。
            map.get(cur).next=map.get(cur.next);
            map.get(cur).random=map.get(cur.random);
            cur=cur.next;
        }
        return map.get(head);
    }

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

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。

// 打印中序遍历
void dfs(Node root) {
    if(root == null) return;
    dfs(root.left); // 左
    System.out.println(root.val); // 根
    dfs(root.right); // 右
}
/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
 //用于保存头节点和尾节点
    public Node pre,head;
    public Node treeToDoublyList(Node root) {
        if(root==null) return null;
        //中序遍历dfs
        dfs(root);
        head.left=pre;
        pre.right=head;
        return head;
    }
    public void dfs(Node cur)
    {
        //到达叶子节点后退出
        if(cur==null) return;
        //递归遍历左子树
        dfs(cur.left);
        if(pre!=null)pre.right=cur;
        else head=cur;
        cur.left=pre;
        pre=cur;
        //递归遍历右子树
        dfs(cur.right);
    }
}

剑指 Offer 37. 序列化二叉树

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

// Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root==null)return "[]";
        //定义StringBuffer可变长度字符串用来保存结果,最后toString()返回结果。
        StringBuffer res=new StringBuffer("[");
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty())
        {
            //队列中元素值可以为空
            TreeNode node= queue.poll();
            if(node!=null)
            {
                res.append(node.val+",");
                queue.add(node.left);
                queue.add(node.right);
            }
            //找到最后为空叶子节点
            else {
                res.append("null,");
            }
        }
        res.deleteCharAt(res.length()-1);
        res.append("]");
        return res.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("[]"))return null;
        String[] vals=data.substring(1,data.length()-1).split(",");
        Queue<TreeNode> queue=new LinkedList<>();
        //定义root节点作为最后返回结果
        TreeNode root=new TreeNode(Integer.parseInt(vals[0]));
        //i作为vals数组下标
        int i=1;
        queue.add(root);
        while(!queue.isEmpty())
        {
            TreeNode node=queue.poll();
            if(!vals[i].equals("null")){
                node.left=new TreeNode(Integer.parseInt(vals[i]));
                queue.add(node.left);
            }
            i++;
            if(!vals[i].equals("null")){
                node.right=new TreeNode(Integer.parseInt(vals[i]));
                queue.add(node.right);
            }
            i++;
        }
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

剑指 Offer 38. 字符串的排列

输入一个字符串,打印出该字符串中字符的所有排列。

你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

class Solution {
    public List<String> res=new LinkedList<>();
    public char[] c;
    public String[] permutation(String s) {
        c=s.toCharArray();
        //全排列,固定一个元素交换其他元素。
        dfs(0);
        return res.toArray(new String[res.size()]);
    }
    public void dfs(int x){
    	//dfs终止条件
        if(x==c.length-1)
        {
            res.add(String.valueOf(c));
            return;
        }
        HashSet<Character> set=new HashSet<>();
        for(int i=x;i<c.length;i++){
            if(set.contains(c[i]))continue;
            set.add(c[i]);
            swap(i,x);
            dfs(x+1);
            swap(i,x);
        }
    }
    public void swap(int a,int b)
    {
        char tmp=c[a];
        c[a]=c[b];
        c[b]=tmp;
    }
}

剑指 Offer 39. 数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

摩尔投票法:摩尔投票法找的其实不是众数,而是占一半以上的数。当数组没有超过一半的数,则可能返回非众数,比如[1, 1, 2, 2, 2, 3, 3],最终返回3。投票法简单来说就是不同则抵消,占半数以上的数字必然留到最后。

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

剑指 Offer 42. 连续子数组的最大和

输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。

要求时间复杂度为O(n)。

class Solution {
    public int maxSubArray(int[] nums) {
        int res=nums[0];
        for(int i=1;i<nums.length;i++)
        {
            nums[i]+=Math.max(nums[i-1],0);
            res=Math.max(res,nums[i]);
        }
        return res;
    }
}

以某个数作为结尾,意思就是这个数一定会加上去,那么要看的就是这个数前面的部分要不要加上去。大于零就加,小于零就舍弃。

剑指 Offer 44. 数字序列中某一位的数字

数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。

请写一个函数,求任意第n位对应的数字。

示例 1:

输入:n = 3
输出:3
示例 2:

输入:n = 11
输出:0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值