Daily Temperatures

题目地址:https://leetcode.com/problems/daily-temperatures/description/

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].

题目要求计算出数组中每一个数字后面第一个比它大的数字与其之间的距离。

首先想到的第一种解法就是用双层循环,对数组中的每个数字进行遍历,然后计算第一个比它大的值与它之间的距离即可,但是这样做的话时间复杂度比较高,时间复杂度为O(n^2),那么我们有没有更快的办法呢,答案是有的。

在这里我们可以利用堆栈对数组中的每一个元素进行控制,注意原数组的数值只是对计算过程的比较起作用,我们最终的结果只与元素的下标有关,所以我们在堆栈中存储每个数字的下标,每次只要遍历到更大的数字的时候,这时候就要对堆栈进行一个pop的操作,这时候也正是我们记录距离的时刻:

public class DailyTemperatures {
    public static int[] dailyTemperatures(int[] temperatures) {
        if (temperatures == null)
            return null;
        if (temperatures.length == 0)
            return temperatures;

        int[] result = new int[temperatures.length];
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < temperatures.length; i++) {
            while (!stack.isEmpty()) {
                if (temperatures[i] > temperatures[stack.peek()]) {
                    int index = stack.pop();
                    result[index] = i - index;
                } else {
                    break;
                }
            }
            stack.push(i);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] temperatures = new int[]{73, 74, 75, 71, 69, 72, 76, 73};
        System.out.println(Arrays.toString(dailyTemperatures(temperatures)));
        return;
    }
}

时间复杂度为O(n),空间复杂度为O(n)。

猜你喜欢

转载自blog.csdn.net/sinat_36246371/article/details/79117560