228. Summary Ranges

本文介绍了一种算法,用于处理已排序且不含重复元素的整数数组,并返回其区间求和的简洁表示形式。该算法考虑了多种特殊情况,如数组长度为0、1或2的情况,并通过一次遍历实现,确保了时间复杂度为O(n),空间复杂度为O(1)。
QUESTION

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”].

THOUGHT

这道题不难,但是需要考虑很多细节,数组长度为0,为1,为2.都要去考虑,这种题就是细节题。

CODE
public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<String>();
        if(nums == null || nums.length == 0)
            return res;
        if(nums.length == 1){
            res.add(nums[0] + "");
            return res;
        }
        for(int i = 0;i < nums.length;i++){
            int begin = nums[i];
            while(i + 1 < nums.length && nums[i] + 1 == nums[i + 1])
                i++;
            if(nums[i] != begin)
                res.add(begin + "->" + nums[i]);
            else
                res.add(begin + "");
        }
        return res;
    }
}
RESULT

时间复杂度为O(n),space complexity is O(1);

二刷CODE
public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();
        if(nums == null || nums.length ==0)
            return res;
        int i = 0;
        while(i < nums.length){
            int begain = nums[i];
            while(i < nums.length - 1 && nums[i + 1] == nums[i] + 1)
                i++;
            if(nums[i] != begain)
                res.add(begain + "->" + nums[i]);
            else
                res.add(begain + "");
            i++;
        }
        return res;
    }
}
import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy import stats plt.rcParams['font.sans-serif'] = ['SimHei'] # 使用黑体显示中文 plt.rcParams['axes.unicode_minus'] = False # 解决保存图像时负号 '-' 显示为方块的问题 def data_preprocessing(df): df['监测时间'] = pd.to_datetime(df['监测时间'], format='%Y-%m-%d %H') df = df.set_index('监测时间') full_range = pd.date_range(start=df.index.min(), end=df.index.max(), freq='h') df_clean = df.reindex(full_range) valid_ranges = { 'PH 值': (6.0, 9.0), '氨氮排放量': (0.01, 1.5), '化学需氧量排放量': (0.05, 5.0) } for col, (min_val, max_val) in valid_ranges.items(): mask = df_clean[col].between(min_val, max_val) df_clean[col] = df_clean[col].where(mask).interpolate(method='spline', order=3) return df_clean def timing_drawing(df): plt.figure(figsize=(15, 9)) plt.subplot(3, 1, 1) plt.plot(df['PH 值'], color='#1f77b4') plt.title('PH 值时序变化趋势', fontproperties='SimHei') plt.ylabel('PH 值', fontproperties='SimHei') plt.subplot(3, 1, 2) plt.plot(df['氨氮排放量'], color='#2ca02c') plt.title('氨氮排放量时序变化趋势', fontproperties='SimHei') plt.ylabel('mg/L', fontproperties='SimHei') plt.subplot(3, 1, 3) plt.plot(df['化学需氧量排放量'], color='#d62728') plt.title('化学需氧量排放量时序变化趋势', fontproperties='SimHei') plt.ylabel('mg/L', fontproperties='SimHei') plt.tight_layout() plt.savefig('时间序列图.png', dpi=300) plt.show() def statistical_analysis(df): stats_summary = df.describe().transpose() median_values = df.median() stats_summary['median'] = median_values.values stats_summary = stats_summary[['mean', 'median', 'std', 'max', 'min']] # 确保输出的表格有正确的列名和指标名字 stats_summary.index.name = '指标' stats_summary.reset_index(inplace=True) stats_summary.columns = ['指标', '均值', '中位数', '标准差', '最大值', '最小值'] print("统计量分析表:") print(stats_summary.to_markdown(index=False)) if __name__ == "__main__": raw_df = pd.read_excel('B 题附件.xls') processed_df = data_preprocessing(raw_df) processed_df.reset_index().to_excel('预处理数据.xlsx', index=True) timing_drawing(processed_df) statistical_analysis(processed_df) 上述代码只需要PH值、氨氮排放量、化学需氧量排放量
最新发布
03-24
这段代码主要用于处理和分析污水监测数据,特别是针对PH值、氨氮排放量和化学需氧量排放量三个关键指标。以下是代码的关键步骤及其功能: ### 代码概述 1. **导入必要的库**: - `pandas` 用于数据处理和操作。 - `matplotlib.pyplot` 用于绘图。 - `numpy` 提供科学计算支持。 - `scipy.stats` 用于统计分析。 2. **设置Matplotlib参数**: - 设置中文字体为黑体 (`SimHei`),以正确显示中文标签。 - 解决保存图像时负号显示为方块的问题。 3. **数据预处理 (`data_preprocessing`)**: - 将`监测时间`列转换为日期时间格式,并设置为索引。 - 创建完整的时间范围,确保数据按小时连续。 - 对异常值进行处理,使用三次样条插值填补缺失值,保留趋势特征。 - 返回清理后的数据框。 4. **绘制时序图 (`timing_drawing`)**: - 绘制PH值、氨氮排放量和化学需氧量排放量的时序变化趋势图。 - 每个图表都有对应的标题和轴标签,并保存为PNG图片。 5. **统计分析 (`statistical_analysis`)**: - 计算并汇总各指标的基本统计量(均值、中位数、标准差、最大值、最小值)。 - 输出统计量分析表。 6. **主程序 (`__main__`)**: - 读取Excel文件中的原始数据。 - 执行数据预处理,并保存预处理后的数据。 - 绘制时序图并进行统计分析。 ### 关键步骤解析 #### 数据预处理 (`data_preprocessing`) ```python def data_preprocessing(df): df['监测时间'] = pd.to_datetime(df['监测时间'], format='%Y-%m-%d %H') df = df.set_index('监测时间') full_range = pd.date_range(start=df.index.min(), end=df.index.max(), freq='h') df_clean = df.reindex(full_range) valid_ranges = { 'PH 值': (6.0, 9.0), '氨氮排放量': (0.01, 1.5), '化学需氧量排放量': (0.05, 5.0) } for col, (min_val, max_val) in valid_ranges.items(): mask = df_clean[col].between(min_val, max_val) df_clean[col] = df_clean[col].where(mask).interpolate(method='spline', order=3) return df_clean ``` #### 绘制时序图 (`timing_drawing`) ```python def timing_drawing(df): plt.figure(figsize=(15, 9)) plt.subplot(3, 1, 1) plt.plot(df['PH 值'], color='#1f77b4') plt.title('PH 值时序变化趋势', fontproperties='SimHei') plt.ylabel('PH 值', fontproperties='SimHei') plt.subplot(3, 1, 2) plt.plot(df['氨氮排放量'], color='#2ca02c') plt.title('氨氮排放量时序变化趋势', fontproperties='SimHei') plt.ylabel('mg/L', fontproperties='SimHei') plt.subplot(3, 1, 3) plt.plot(df['化学需氧量排放量'], color='#d62728') plt.title('化学需氧量排放量时序变化趋势', fontproperties='SimHei') plt.ylabel('mg/L', fontproperties='SimHei') plt.tight_layout() plt.savefig('时间序列图.png', dpi=300) plt.show() ``` #### 统计分析 (`statistical_analysis`) ```python def statistical_analysis(df): stats_summary = df.describe().transpose() median_values = df.median() stats_summary['median'] = median_values.values stats_summary = stats_summary[['mean', 'median', 'std', 'max', 'min']] # 确保输出的表格有正确的列名和指标名字 stats_summary.index.name = '指标' stats_summary.reset_index(inplace=True) stats_summary.columns = ['指标', '均值', '中位数', '标准差', '最大值', '最小值'] print("统计量分析表:") print(stats_summary.to_markdown(index=False)) ``` ### 总结 该代码实现了对污水监测数据的全面处理和分析,涵盖了数据预处理、时序图绘制以及统计分析等多个方面。通过这些步骤,能够清晰地展示和理解污水排放指标的时间变化趋势及其统计数据特征,为后续的数学建模和预测提供坚实的基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值