LeetCode 739 Daily Temperatures (思维)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/89601761

Given a list of daily temperatures T, return a list such 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 of temperatures T = [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].

题目链接:https://leetcode.com/problems/daily-temperatures/

题目大意:求比当前数字大的第一个数的下标

题目分析:从后向前,bigger数组存当前位置之后比当前位置大的第一个数所在的位置,不存在则设为n,当T[i]<T[i+1]时答案显然,否则通过bigger数组查找比T[i]大的第一个位置

4ms,时间击败98.36%

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int n = T.length;
        int[] bigger = new int[n];
        int[] ans = new int[n];
        ans[n - 1] = 0;
        bigger[n - 1] = n;
        for (int i = n - 2; i >= 0; i--) {
            if (T[i] < T[i + 1]) {
                bigger[i] = i + 1;
                ans[i] = 1;
            } else {
                int p = bigger[i + 1];
                while (p != n && T[p] <= T[i]) {
                    p = bigger[p];
                }
                if (p == n) {
                    bigger[i] = n;
                    ans[i] = 0;
                } else {
                    bigger[i] = p;
                    ans[i] = p - i;
                }
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Tc_To_Top/article/details/89601761
今日推荐