leetcode错题记录(2)

剑指 Offer II 038. 每日温度icon-default.png?t=M7J4https://leetcode.cn/problems/iIQa4I/

 这道题的难度是中等。看到这道题的时候首先想到的是双层遍历,主要思想是:用i记录要修改的元素下标,用j遍历其后面的元素,把第一个比其大的元素与其的下标差作为数组新元素,然后直接在数组上修改返回。

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int temp=-1;
        for(int i=0; i<temperatures.length; i++){
            for(int j=i; j<temperatures.length; j++){
                temp=temperatures[i];
                if(temperatures[j]>temperatures[i]){
                    temperatures[i]=j-i;
                    break;
                }
            }
            if(temp==temperatures[i]){
                temperatures[i]=0;
            }
        }
        return temperatures;
    }
}

我这里设置了一个temp来判断数组某一元素在遍历过程中是否已被修改,如果没有被修改则说明在其后的温度都要被它低,则直接把它设置为0。但提交失败。后面检查发现这里不应该用一个变量来判断是否被修改,因为存在数组中元素原来的值等于修改后的值这种情况,这时候是无法判断出来的。后面我修改了一下,在每次遍历后加一个if语句,判断j是否到了数组末尾,若到了数组末尾则说明在之前都未被修改。果然提交成功了,但是算法开销有点大,还有待改进。

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        for(int i=0; i<temperatures.length; i++){
            for(int j=i; j<temperatures.length; j++){
                if(temperatures[j]>temperatures[i]){
                    temperatures[i]=j-i;
                    break;
                }
                if(j==temperatures.length-1){
                    temperatures[i]=0;
                }
            }
        }
        return temperatures;
    }
}

时间复杂度为O(n2)

翻看了一下官方解法,用的是单调栈,降低了时间复杂度。

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int length = temperatures.length;
        int[] ans = new int[length];
        Deque<Integer> stack = new LinkedList<Integer>();
        for (int i = 0; i < length; i++) {
            int temperature = temperatures[i];
            while (!stack.isEmpty() && temperature > temperatures[stack.peek()]) {
                int prevIndex = stack.pop();
                ans[prevIndex] = i - prevIndex;
            }
            stack.push(i);
        }
        return ans;
    }
}

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/iIQa4I/solution/mei-ri-wen-du-by-leetcode-solution-vh9j/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值