315. Count of Smaller Numbers After Self

本文介绍了一种算法问题的解决方法,即计算数组中每个元素右侧比其小的元素数量。通过三种不同的方法——插入排序法、使用C++ STL函数简化代码及构建二分搜索树,详细阐述了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Return the array [2, 1, 1, 0].

题目地址

题意:
计算数组中元素的右侧比它小的元素个数

思路:
1、插入排序法:
建立新的有序数组,将原数组中的元素从后向前依次插入到新数组中,每次插入前利用二分法找到元素应该插入的位置,找到位置的下标就是该元素在原数组中右侧比它小的元素的个数。

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {  //记住vector做参数的用法
        vector<int> t, res(nums.size());    //t是新的有序数组,res用来保存答案
        for (int i = nums.size() - 1; i >= 0; --i) {  //从后往前插入元素
            int left = 0, right = t.size();    
            while (left < right) {   //二分法查找应插入的位置
                int mid = left + (right - left) / 2;
                if (t[mid] >= nums[i]) right = mid;
                else left = mid + 1;
            }
            res[i] = right;   //保存找到的位置下标
            t.insert(t.begin() + right, nums[i]);  //插入元素
        }
        return res;
    }
};

2、此外,可以利用C++中STL自带的函数来实现上述代码中的二分搜索部分,简化代码。主要利用了lower_bound()和distance()两个函数。

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {
        vector<int> t, res(nums.size());
        for (int i = nums.size() - 1; i >= 0; --i) {
            int d = distance(t.begin(), lower_bound(t.begin(), t.end(), nums[i]));
            res[i] = d;
            t.insert(t.begin() + d, nums[i]);
        }
        return res;
    }
};

3、二分搜索树
首先构造一棵二分搜索树,稍有不同的地方是我们需要加一个变量smaller来记录已插入结点中比当前节点值小的所有节点的个数。我们每插入一个节点,会判断其与根节点的大小,如果新的节点值小于根节点值,则增加根节点的smaller,并会插入到左子树中,继续递归调用左子节点的insert。如果节点值大于根节点值,则需要递归调用右子节点的insert并加上根节点的smaller,并加1:

class Solution {
public:
    struct Node {
        int val, smaller;  //val 保存结点的值,smaller保存该结点的左子树中结点个数,即到当前时刻插入的元素中比val小的元素的个数
        Node *left, *right;
        Node(int v, int s) : val(v), smaller(s), left(NULL), right(NULL) {} //结构体构造函数
    };

    int insert(Node *&root, int v) {
        if (!root) return (root = new Node(v, 0)), 0;  //逗号表达式,等价于root = new Node(v,0);return 0;如果为空在,则构造新的结点。
        if (root->val > v) return root->smaller++, insert(root->left, v);//如果V小于根节点的val,则将根节点中的smaller+1,向左子树遍历,并返回左子树返回的值
        else return insert(root->right, v) + root->smaller + (root->val < v ? 1 : 0); //如果v大于根节点的val,则向右子树遍历,返回值中的三项依次代表,右子树中比v小的元素个数,左子树中比v小的元素个数,root中的val是否比v小。
    }

    vector<int> countSmaller(vector<int>& nums) {
        vector<int> res(nums.size());
        Node *root = NULL;
        for (int i = nums.size() - 1; i >= 0; --i) {   //从后向前依次插入原数组的元素构造二叉树,同时保存结果。在插入nums[i]时,树中元素都是num[i]右边的元素。
            res[i] = insert(root, nums[i]);
        }
        return res;
    }
};

C++知识点

  • 逗号表达式:
    逗号表达式的语法为:表达式1,表达式2,…,表达式n
    C++顺序计算表达式1,表达式2,…,表达式n的值。
    逗号表达式是有值的,逗号表达式的值为最后一个子表达式的值。
  • lower_bound()查找第一个不小于某值元素的位置。
  • distance()计算两个迭代器之间的距离。
<think>我们之前尝试使用pheatmap时遇到了“Error: The width you set is smaller than the sum of gaps”错误,这通常是由于热图的整体宽度设置过小,无法容纳所有列和间隙。为了解决这个问题,我们决定更换到ComplexHeatmap包,它提供了更灵活的空间控制。 在ComplexHeatmap中,我们可以通过精确控制热图单元的大小和间隙来避免此类错误。以下是具体步骤: 1. 计算热图所需的总宽度:总宽度 = (列数 * 每个单元格的宽度) + (列间隙的总和) + (其他元素如行名、图例等的宽度) 2. 使用`unit`函数设置合适的单元格宽度和高度 3. 通过`draw`函数绘制时,可以指定整个热图对象的宽度 我们将使用以下代码实现: 注意:我们保留之前的需求,包括: - 双侧行标签(左侧和右侧都有行名) - 自定义颜色(低亮度渐变:蓝-黄-红) - 处理缺失值(NA显示为白色) - 不进行聚类 代码实现如下:</think>针对热图绘制中出现的 "width you set is smaller than sum of gaps" 错误,我将使用 **ComplexHeatmap** 包提供完整的解决方案。这个错误通常发生在热图整体宽度设置小于列间隙总和时,而 ComplexHeatmap 提供了更灵活的尺寸控制机制。 ### 完整解决方案 ```r # 安装和加载包 if (!require("BiocManager")) install.packages("BiocManager") BiocManager::install("ComplexHeatmap") library(ComplexHeatmap) library(circlize) # 读取数据 data <- read.csv("HorA.csv", row.names = 1) mat <- as.matrix(data) mat[mat == "***"] <- NA mat <- apply(mat, 2, as.numeric) # 创建低亮度渐变颜色 col_fun <- colorRamp2( breaks = c(0, 50, 100), colors = c("#084594", "#f7fcb9", "#cb181d") ) # 计算单元格尺寸(核心解决点) cell_width <- unit(4, "mm") # 单个单元格宽度 cell_height <- unit(4, "mm") # 单个单元格高度 total_width <- ncol(mat) * cell_width # 总宽度计算 # 创建行注释(右侧标签) row_ha <- rowAnnotation( right_labels = anno_text( rownames(mat), gp = gpar(fontsize = 8), just = "center", location = 0.5 ), show_annotation_name = FALSE ) # 创建热图主体 ht <- Heatmap( mat, name = "相似度 (%)", col = col_fun, na_col = "white", cluster_rows = FALSE, cluster_columns = FALSE, # 尺寸控制(解决宽度错误的核心) width = total_width, # 显式设置总宽度 height = nrow(mat) * cell_height, # 显式设置总高度 # 标签设置 row_names_side = "left", row_names_gp = gpar(fontsize = 8), column_names_gp = gpar(fontsize = 8, rot = 45), # 间隙控制(避免间隙总和超过宽度) row_gap = unit(0.5, "mm"), # 减小行间隙 column_gap = unit(0.5, "mm"), # 减小列间隙 # 右侧标签 right_annotation = row_ha ) # 绘制热图(自动调整布局) draw(ht, heatmap_legend_side = "right", padding = unit(c(2, 2, 2, 2), "mm")) # 添加边距 ``` ### 关键改进说明 1. **显式尺寸控制**: - 使用 `unit(4, "mm")` 明确定义单元格尺寸 - 总宽度计算:$W_{\text{total}} = n_{\text{cols}} \times W_{\text{cell}}$ - 避免间隙总和超过总宽度的问题[^1] 2. **间隙优化**: - 减小行/列间隙:`row_gap = unit(0.5, "mm")` - 间隙总和计算:$G_{\text{total}} = (n_{\text{cols}} - 1) \times G_{\text{col}}$ - 确保满足 $W_{\text{total}} > G_{\text{total}}$ 3. **自适应布局**: - `draw()` 自动处理元素布局 - `padding` 参数添加安全边距 - 支持响应式调整(缩放时保持比例)[^2] 4. **错误预防机制**: ```r # 安全验证(可选) min_width <- (ncol(mat) - 1) * 1.5 + 5 # 最小宽度计算 if(convertWidth(total_width, "mm", valueOnly = TRUE) < min_width) { warning("建议增加单元格宽度至", min_width/ncol(mat), "mm") } ``` ### 尺寸调整建议 | 参数 | 建议值 | 作用 | |------|--------|------| | `cell_width` | 3-6 mm | 控制列宽 | | `cell_height` | 3-6 mm | 控制行高 | | `row_gap` | 0.3-1 mm | 行间距 | | `column_gap` | 0.3-1 mm | 列间距 | | `padding` | 2-5 mm | 整体边距 | ### 输出优化技巧 ```r # 保存高分辨率图片 png("heatmap.png", width = 2000, height = 1200, res = 300) draw(ht) dev.off() # 调整图例位置 draw(ht, heatmap_legend_side = "bottom", padding = unit(c(5, 15, 5, 5), "mm")) ``` 此方案通过精确控制物理尺寸彻底解决了宽度错误问题,同时保持了双侧标签和自定义颜色的需求[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值