[Leetcode] 739. Daily Temperatures 解题报告

本文介绍了一种高效的算法,用于预测每日气温变化趋势。该算法通过栈结构处理一系列气温数据,为每一天计算出直到气温升高的天数。适用于气温预测场景,算法的时间复杂度和空间复杂度均为O(n)。

题目

Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

思路

我们定义一个栈,然后在遍历温度的时候分别做如下处理:

1)如果当天的温度比第二天的温度高,那么我们暂时还无法确定需要等多少天才能有更高的温度,所以就将当天的温度入栈。

2)如果当天的温度比第二天的温度低,那么它需要等待的天数就是1。但是此时我们需要更新栈顶元素对应的那天的等待时间。我们以题目中给出的例子为例来讲解:[73, 74, 75, 71, 69, 72, 76, 73]。扫描73, 74的时候,其对应结果为1;当遇到75的时候,由于75 > 71,所以我们将75入栈(此时栈内元素为75),71也同理(此时栈内元素为75,71)。当遇到69的时候,69 < 72,所以69的对应结果为1,但是由于72大于栈顶元素71,所以此时可以修改71对应的等待天数,即为72对应的天数索引与71对应的天数索引,然后71出栈(此时栈内元素为75);当处理72的时候,结果为1,但是由于76大于栈顶元素75,所以修改75的等待天数,并出栈(此时栈内为空)。当处理76的时候,76需入栈。由于再也没有比76大的元素,并且73之后也没有元素了,所以76,73对应的等待天数就都为0了,在程序中并没有做处理。

算法的空间复杂度为O(n),时间复杂度也为O(n),这是因为for循环里面的while循环中,每个元素最多出一次栈,所以while总的执行次数是O(n)量级的。

代码

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> ret(n, 0);
        stack<pair<int, int>> s;
        for (int i = 0; i < n - 1; ++i) {
            if (temperatures[i] < temperatures[i + 1]){
                ret[i] = 1;
                while (!s.empty() && temperatures[i + 1] > s.top().first) {
                    ret[s.top().second] = i + 1 - s.top().second;
                    s.pop();
                } 
            } 
            else {
                s.push(make_pair(temperatures[i], i));
            }
        }
        return ret;
    }
};
以下是对原代码的优化,主要解决了分割方式可能不准确的问题,使用正则表达式来匹配可能的分隔符,同时处理了可能出现的异常情况: ```python import os import re folder_path = 'E:\本基\新范围焚风强度\(新)选择数据v2\Tem_Rhu' for filename in os.listdir(folder_path): if filename.endswith('.txt'): file_path = os.path.join(folder_path, filename) daily_min_temperatures = {} try: with open(file_path, 'r', encoding='utf-8') as file: for line in file: # 使用正则表达式匹配可能的分隔符 parts = re.split(r'[ \t,;]+', line.strip()) if len(parts) >= 5: year = parts[0] month = parts[1] day = parts[2] try: temperature = float(parts[4]) date = f'{year}-{month}-{day}' if date not in daily_min_temperatures: daily_min_temperatures[date] = temperature elif temperature < daily_min_temperatures[date]: daily_min_temperatures[date] = temperature except ValueError: print(f"在文件 {filename} 中遇到无法转换为浮点数的温度值: {parts[4]}") except Exception as e: print(f"处理文件 {filename} 时出现错误: {e}") output_filename = f'{os.path.splitext(filename)[0]}_min_tem.txt' output_path = os.path.join(folder_path, output_filename) try: with open(output_path, 'w', encoding='utf-8') as output_file: for date, min_temp in daily_min_temperatures.items(): output_file.write(f'{date}\t{min_temp}\n') except Exception as e: print(f"写入文件 {output_filename} 时出现错误: {e}") ``` ### 优化点说明: 1. **分隔符处理**:使用 `re.split(r'[ \t,;]+', line.strip())` 来匹配可能的分隔符(空格、制表符、逗号、分号),避免了原代码中固定使用制表符分割的问题。 2. **异常处理**:添加了 `try-except` 块来捕获和处理可能出现的异常,如文件读取错误、温度值无法转换为浮点数等。 3. **编码指定**:在打开文件时指定了 `encoding='utf-8'`,避免编码问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值