Programming questions-algorithm-medium-leetcode-739. Daily temperature

Programming questions-algorithm-medium-leetcode-739. Daily temperature

1. Topic: Daily temperature

insert image description here
2. Programming answer
Seeing the title, you can think of using a two-way queue to record the corresponding temperature and subscript value. Then traverse the temperature temperatures. When the traversed temperature value (temp) is higher than the temperature of the first element in the queue (firstTempInQue), you can get the result of the first element in the queue.

If the current temperature value (temp) is lower than the temperature of the first element in the queue (firstTempInQue), put it at the head of the queue.

2.1 Method 1

Method 1 is easier to understand, customize the Node class and queue, and answer

class Node {
    
    
    int temperature;
    int index;

    public Node(int tmp, int idx) {
    
    
        this.temperature = tmp;
        this.index = idx;
    }
}

class Solution {
    
    
    public int[] dailyTemperatures(int[] temperatures) {
    
    
        int[] res = new int[temperatures.length];
        Deque<Node> queue = new LinkedList<>();

        for (int i=0; i<temperatures.length; i++) {
    
    
            Node node = new Node(temperatures[i], i);

            // 如果队列非空,且对首元素温度低于当前遍历的温度值,则找到队首对应的结果
            while (!queue.isEmpty() && queue.peekFirst().temperature<node.temperature) {
    
    
                Node firstNode = queue.pollFirst();
                res[firstNode.index] = node.index - firstNode.index;
            }
            // 队列为空,或者队首的温度大于当前遍历温度值,则将当前温度值放在队首
            queue.offerFirst(node);
        }

        // 队列中剩下的元素,代表找不到温度比他们高的值,因此结果都为0
        return res;
    }
}

The result after submission is shown in the figure below. It can be seen that the time complexity and space complexity are relatively good.
insert image description here

2.1 Method 2:

The second way is to save the subscript value of the corresponding temperature in the queue without using the custom class Node, and use the subscript to judge. Of course, the principle is basically the same as the first method. If you understand the first method, the second method will be easy to understand.

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;
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/xueping_wu/article/details/127142087