每日算法11_2020-11-17

来源:题库 - 力扣 (LeetCode) (leetcode-cn.com)。侵删。

题目一

101. 对称二叉树

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

	1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

	1
   / \
  2   2
   \   \
   3    3

进阶:

你可以运用递归和迭代两种方法解决这个问题吗?

我的答案

递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        
        return check(root, root);
    }

    // 检查传过来的左右节点的值左右子树是否相同
    public static boolean check(TreeNode leftNode, TreeNode rightNode){
        if(leftNode == null && rightNode == null) return true;
        if(leftNode == null || rightNode == null) return false;

        // 检查 
        // 左右节点的值
        // 左节点的左子树与右节点的右子树
        // 左节点的右子树与右节点的左子树
        // 是否相等
        return leftNode.val == rightNode.val && 
               check(leftNode.left, rightNode.right) && 
               check(leftNode.right, rightNode.left);
    }

}

复杂度分析

假设树上一共 n 个节点。

时间复杂度:这里遍历了这棵树,渐进时间复杂度为 O(n)。
空间复杂度:这里的空间复杂度和递归使用的栈空间有关,这里递归层数不超过 n,故渐进空间复杂度为 O(n)。

我认为的迭代

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;

        TreeNode rootroot = root; // 用于标记最顶层根节点
        TreeNode root2 = root; // 复制一份引用

        Stack<TreeNode> stack = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();

        // 一个栈装左子树,一个栈装右子树
        // 就是一边直冲最底层左子树,一边直冲最右右子树
        // 就是类似中序遍历一样,左右子树只不过是相反的而已
        while(!stack.isEmpty() || !stack2.isEmpty() || root != null || root2 != null){
            int leftVal = 0, rightVal = 0;
            while(root != null){
                stack.push(root); // 把本身放进栈
                root = root.left;
                // 出这个循环说明达到最左边的节点了
            }
            while(root2 != null){
                stack2.push(root2); // 把本身放进栈
                root2 = root2.right;
                // 出这个循环说明达到最右边的节点了
            }

            // 弹出最上面的节点(即为上行代码比较值的节点)
            root = stack.pop();
            root2 = stack2.pop();
            leftVal = root.val; // 记录值
            rightVal = root2.val; // 记录值

            System.out.println(leftVal + " - " + rightVal);
            // 在判断值前先判断两个栈内的元素是否一样多,对称树应该时一样多的
            if(stack.size() != stack2.size()) return false;

            if (leftVal != rightVal) return false; // 判断左右值,不同即false
            
            // 有一个回到顶层节点另一个却没回到顶层节点时直接返回false
            if(root == rootroot && root2 != rootroot) return false;
            if(root2 == rootroot && root != rootroot) return false;
            // 判断是否回到了最顶层根节点
            if(root == root2) return true; // 回到了说明左右子树一样,这时就必要再往下判断了

            // 没回到最顶层根节点,就要判断左子树的右节点和右子树的左节点值是否相同
            root = root.right;
            root2 = root2.left;
        }

        return stack.isEmpty() && stack2.isEmpty();
    }
}

正确的迭代

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return check(root, root);
    }

    public boolean check(TreeNode u, TreeNode v) {
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(u);
        q.offer(v);
        while (!q.isEmpty()) {
            u = q.poll();
            v = q.poll();
            if (u == null && v == null) {
                continue;
            }
            if ((u == null || v == null) || (u.val != v.val)) {
                return false;
            }

            q.offer(u.left);
            q.offer(v.right);

            q.offer(u.right);
            q.offer(v.left);
        }
        return true;
    }
}

复杂度分析

时间复杂度:O(n),同「递归」。
空间复杂度:这里需要用一个队列来维护节点,每个节点最多进队一次,出队一次,队列中最多不会超过 n 个点,故渐进空间复杂度为 O(n)。

题目二

112. 路径总和

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \      \
    7    2      1

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

我的答案

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        return root != null && maxValue(root, 0, sum); // 添加进去了说明没有这个路径值,就取反为false
    }

    public boolean maxValue(TreeNode node, int n, int sum){
        if (node == null) return false;
        if (node.left == null && node.right == null){
            // 说明到叶子节点了,判断此时和会不会等于sum
            n += node.val;
            return n == sum;
        }else{
            // 不为null就往下继续找节点
            n += node.val;
            return maxValue(node.left, n, sum) || maxValue(node.right, n, sum);
        }
    }
}
广度优先算法
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        Queue<TreeNode> queNode = new LinkedList<TreeNode>();
        Queue<Integer> queVal = new LinkedList<Integer>();
        queNode.offer(root);
        queVal.offer(root.val);
        while (!queNode.isEmpty()) {
            TreeNode now = queNode.poll();
            int temp = queVal.poll();
            if (now.left == null && now.right == null) {
                if (temp == sum) {
                    return true;
                }
                continue;
            }
            if (now.left != null) {
                queNode.offer(now.left);
                queVal.offer(now.left.val + temp);
            }
            if (now.right != null) {
                queNode.offer(now.right);
                queVal.offer(now.right.val + temp);
            }
        }
        return false;
    }
}

复杂度分析

时间复杂度:O(N),其中 NN 是树的节点数。对每个节点访问一次。

空间复杂度:O(N),其中 NN 是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。

递归
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            return sum == root.val;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

复杂度分析

时间复杂度:O(N),其中 NN 是树的节点数。对每个节点访问一次。

空间复杂度:O(H),其中 HH 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为 O(\log N)。

题目三

1656. 设计有序流

有 n 个 (id, value) 对,其中 id 是 1 到 n 之间的一个整数,value 是一个字符串。不存在 id 相同的两个 (id, value) 对。

设计一个流,以 任意 顺序获取 n 个 (id, value) 对,并在多次调用时 按 id 递增的顺序 返回一些值。

实现 OrderedStream 类:

OrderedStream(int n) 构造一个能接收 n 个值的流,并将当前指针 ptr 设为 1 。
String[] insert(int id, String value) 向流中存储新的 (id, value) 对。存储后:
如果流存储有 id = ptr 的 (id, value) 对,则找出从 id = ptr 开始的 最长 id 连续递增序列 ,并 按顺序 返回与这些 id 关联的值的列表。然后,将 ptr 更新为最后那个 id + 1 。
否则,返回一个空列表。

示例:

img

图片来自于leetcode,侵删。

输入
[“OrderedStream”, “insert”, “insert”, “insert”, “insert”, “insert”]
[[5], [3, “ccccc”], [1, “aaaaa”], [2, “bbbbb”], [5, “eeeee”], [4, “ddddd”]]
输出
[null, [], [“aaaaa”], [“bbbbb”, “ccccc”], [], [“ddddd”, “eeeee”]]

解释
OrderedStream os= new OrderedStream(5);
os.insert(3, “ccccc”); // 插入 (3, “ccccc”),返回 []
os.insert(1, “aaaaa”); // 插入 (1, “aaaaa”),返回 [“aaaaa”]
os.insert(2, “bbbbb”); // 插入 (2, “bbbbb”),返回 [“bbbbb”, “ccccc”]
os.insert(5, “eeeee”); // 插入 (5, “eeeee”),返回 []
os.insert(4, “ddddd”); // 插入 (4, “ddddd”),返回 [“ddddd”, “eeeee”]

提示:

1 <= n <= 1000
1 <= id <= n
value.length == 5
value 仅由小写字母组成
每次调用 insert 都会使用一个唯一的 id
恰好调用 n 次 insert

我的答案

class OrderedStream {

    String[] ret;
    int ptr = 0;
    
    public OrderedStream(int n) {
        this.ptr = 1;
        ret = new String[n];
    }
    
    public List<String> insert(int id, String value) {
        ret[id-1] = value; // 先添加值

        List<String> retList = new ArrayList<>();

        // 返回值,从当前指针往后所有长度的
        for(int i=ptr-1; i<ret.length; i++){
            // System.out.println("i:" + i + ", id:" + id+ ", ptr: " + ptr) ;
            if((id != ptr || ret[i] == null) && ret[ptr-1] == null){
                break;
            }else{
                retList.add(ret[i]);

                ptr++;
//                System.out.println("" + retList + ", " + ptr);
            }
        }
        return retList;
    }
}

/**
 * Your OrderedStream object will be instantiated and called as such:
 * OrderedStream obj = new OrderedStream(n);
 * List<String> param_1 = obj.insert(id,value);
 */

我的思路不是很清晰。

别人清晰的解答

解题思路

难点就在于ptr的指向位置,从动图可以直接看出来,ptr表示的是连续有值的序列的下一位。
即从ptr往流的末尾开始遍历,遇到空的就停止,不空就+1;

class OrderedStream {
    String[] stream;
    int ptr = 0;
    public OrderedStream(int n) {
        // 根据长度创建String数组保存值
        stream = new String[n];
    }
    
    public List<String> insert(int id, String value) {
        // id从1起始,所以减1
        stream[id-1] = value;
        // 要返回的数组
        List<String> list = new ArrayList<>();
        // 从ptr开始,直到数组的末尾
        for (int i = ptr; i < stream.length; i++) {
            // 如果遇到流中的空值,跳出循环直接返回list
            if (stream[i] == null) {
                break;
            } else { // 如果该处不为空值,那么ptr就可以到这个地方,返回的list中也应包括这个值
                ptr++;
                list.add(stream[i]);
            }
        }
        return list;
    }
}

/**
 * Your OrderedStream object will be instantiated and called as such:
 * OrderedStream obj = new OrderedStream(n);
 * List<String> param_1 = obj.insert(id,value);
 */

作者:Fisnake
链接:https://leetcode-cn.com/problems/design-an-ordered-stream/solution/javashuang-bai-gen-ju-ti-yi-fan-yi-jiu-hao-shi-xia/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值