牛客题解 | 信封嵌套

题目## 题目

题目链接

解题思路

这是一个二维的最长递增子序列( LIS \text{LIS} LIS)问题,可以通过以下步骤解决:

  1. 首先对信封按照宽度升序排序,当宽度相同时按照长度降序排序
  2. 这样排序后,我们只需要在长度上找最长递增子序列
  3. 使用二分查找优化的 LIS \text{LIS} LIS 算法:
    • 维护一个数组 d p dp dp d p [ i ] dp[i] dp[i] 表示长度为 i + 1 i+1 i+1 的递增子序列的最小结尾值
    • 对于每个数,二分查找它在 d p dp dp 中的位置并更新
      这样可以达到 O ( n log ⁡ n ) \mathcal{O}(n\log n) O(nlogn) 的时间复杂度。

代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int maxEnvelopes(vector<vector<int>>& envelopes) {
    // 按宽度升序排序,宽度相同时按长度降序排序
    sort(envelopes.begin(), envelopes.end(), 
        [](const vector<int>& a, const vector<int>& b) {
            return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
        });
    
    // 在长度上找最长递增子序列
    vector<int> dp;
    for(const auto& envelope : envelopes) {
        int height = envelope[1];
        auto it = lower_bound(dp.begin(), dp.end(), height);
        if(it == dp.end()) {
            dp.push_back(height);
        } else {
            *it = height;
        }
    }
    
    return dp.size();
}

int main() {
    int n;
    cin >> n;
    vector<vector<int>> envelopes(n, vector<int>(2));
    for(int i = 0; i < n; i++) {
        cin >> envelopes[i][0] >> envelopes[i][1];
    }
    cout << maxEnvelopes(envelopes) << endl;
    return 0;
}
import java.util.*;

public class Main {
    public static int maxEnvelopes(int[][] envelopes) {
        // 按宽度升序排序,宽度相同时按长度降序排序
        Arrays.sort(envelopes, (a, b) -> 
            a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
        
        // 在长度上找最长递增子序列
        int[] dp = new int[envelopes.length];
        int len = 0;
        for(int[] envelope : envelopes) {
            int index = Arrays.binarySearch(dp, 0, len, envelope[1]);
            if(index < 0) {
                index = -(index + 1);
            }
            dp[index] = envelope[1];
            if(index == len) {
                len++;
            }
        }
        
        return len;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] envelopes = new int[n][2];
        for(int i = 0; i < n; i++) {
            envelopes[i][0] = sc.nextInt();
            envelopes[i][1] = sc.nextInt();
        }
        System.out.println(maxEnvelopes(envelopes));
        sc.close();
    }
}
def max_envelopes(envelopes):
    # 按宽度升序排序,宽度相同时按长度降序排序
    envelopes.sort(key=lambda x: (x[0], -x[1]))
    
    # 在长度上找最长递增子序列
    dp = []
    for _, height in envelopes:
        left, right = 0, len(dp)
        while left < right:
            mid = (left + right) // 2
            if dp[mid] < height:
                left = mid + 1
            else:
                right = mid
        if left == len(dp):
            dp.append(height)
        else:
            dp[left] = height
    
    return len(dp)

n = int(input())
envelopes = []
for _ in range(n):
    w, h = map(int, input().split())
    envelopes.append([w, h])
print(max_envelopes(envelopes))

算法及复杂度

  • 算法:排序 + 二分查找优化的最长递增子序列
  • 时间复杂度: O ( n log ⁡ n ) \mathcal{O}(n\log n) O(nlogn),排序需要 O ( n log ⁡ n ) \mathcal{O}(n\log n) O(nlogn) LIS \text{LIS} LIS 也需要 O ( n log ⁡ n ) \mathcal{O}(n\log n) O(nlogn)
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n),需要一个 d p dp dp 数组

题目链接

解题思路

1. 基本原理

  • 后序遍历:左子树 -> 右子树 -> 根节点
  • 中序遍历:左子树 -> 根节点 -> 右子树
  • 关键点:后序遍历的最后一个元素一定是根节点
2. 解题步骤

以输入 [2,1,4,3,5](中序)和 [2,4,5,3,1](后序)为例:

  1. 找到根节点

    • 后序遍历的最后一个元素1是根节点
  2. 在中序遍历中定位根节点

    • 中序:[2, (1), 4,3,5]
    • 1的位置将中序序列分成左右子树
  3. 划分子树

    • 左子树:中序 [2],后序 [2]
    • 右子树:中序 [4,3,5],后序 [4,5,3]
  4. 递归构建

    • 对左右子树重复上述过程
    • 左子树:只有一个节点2
    • 右子树:根节点是3,继续划分
3. 图解过程
初始序列:
中序:[2,1,4,3,5]
后序:[2,4,5,3,1]

第一层:
根节点:1
左子树:[2]
右子树:[4,3,5]

构造结果:
     1
    / \
   2   3
      / \
     4   5
4. 注意事项
  1. 确保输入序列长度相等
  2. 处理空树的情况
  3. 注意数组边界
  4. 保存根节点在中序遍历中的位置可以用哈希表优化

代码

class Solution {
private:
    unordered_map<int, int> map;  // 存储中序遍历中值到索引的映射
    vector<int> post;             // 存储后序遍历数组
    
    TreeNode* build(int inStart, int inEnd, int postStart, int postEnd) {
        // 递归终止条件
        if (inStart > inEnd || postStart > postEnd) {
            return nullptr;
        }
        
        // 创建根节点(后序遍历的最后一个元素)
        TreeNode* root = new TreeNode(post[postEnd]);
        
        // 在中序遍历中找到根节点的位置
        int rootIndex = map[root->val];
        
        // 计算左子树的节点个数
        int leftSize = rootIndex - inStart;
        
        // 递归构建左右子树
        root->left = build(inStart, rootIndex - 1, postStart, postStart + leftSize - 1);
        root->right = build(rootIndex + 1, inEnd, postStart + leftSize, postEnd - 1);
        
        return root;
    }
    
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        // 保存后序遍历数组
        post = postorder;
        
        // 构建中序遍历的值到索引的映射
        for (int i = 0; i < inorder.size(); i++) {
            map[inorder[i]] = i;
        }
        
        // 调用递归函数构建树
        return build(0, inorder.size() - 1, 0, postorder.size() - 1);
    }
};
import java.util.*;

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private Map<Integer, Integer> map = new HashMap<>();  // 存储中序遍历中值到索引的映射
    private int[] post;  // 存储后序遍历数组
    
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        post = postorder;
        
        // 构建中序遍历的值到索引的映射
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        
        // 调用递归函数构建树
        return build(0, inorder.length - 1, 0, postorder.length - 1);
    }
    
    private TreeNode build(int inStart, int inEnd, int postStart, int postEnd) {
        // 递归终止条件
        if (inStart > inEnd || postStart > postEnd) {
            return null;
        }
        
        // 创建根节点(后序遍历的最后一个元素)
        TreeNode root = new TreeNode(post[postEnd]);
        
        // 在中序遍历中找到根节点的位置
        int rootIndex = map.get(root.val);
        
        // 计算左子树的节点个数
        int leftSize = rootIndex - inStart;
        
        // 递归构建左右子树
        root.left = build(inStart, rootIndex - 1, postStart, postStart + leftSize - 1);
        root.right = build(rootIndex + 1, inEnd, postStart + leftSize, postEnd - 1);
        
        return root;
    }
}
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        # 创建中序遍历的值到索引的映射
        index_map = {val: i for i, val in enumerate(inorder)}
        
        def build(in_start: int, in_end: int, post_start: int, post_end: int) -> TreeNode:
            # 递归终止条件
            if in_start > in_end or post_start > post_end:
                return None
            
            # 创建根节点(后序遍历的最后一个元素)
            root_val = postorder[post_end]
            root = TreeNode(root_val)
            
            # 在中序遍历中找到根节点的位置
            root_index = index_map[root_val]
            
            # 计算左子树的节点个数
            left_size = root_index - in_start
            
            # 递归构建左右子树
            root.left = build(in_start, root_index - 1, 
                            post_start, post_start + left_size - 1)
            root.right = build(root_index + 1, in_end, 
                             post_start + left_size, post_end - 1)
            
            return root
        
        return build(0, len(inorder) - 1, 0, len(postorder) - 1)

算法及复杂度分析

  • 算法:递归,树的遍历
  • 时间复杂度: O ( n ) \mathcal{O}(n) O(n),每个节点都需要处理一次
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n),需要存储哈希表和递归调用栈

优化方案

  1. 使用哈希表存储中序遍历中节点值与下标的映射,避免重复查找
  2. 使用数组下标而不是切片,减少空间使用
  3. 可以传递边界索引而不是创建新的子数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值