做网站滨州,益阳网站建设公司有哪些,php笔记网站,微信网站方案题目
输入一个数组#xff0c;它的每个数字是某天的温度。请计算每天需要等几天才会出现更高的温度。例如#xff0c;如果输入数组[35#xff0c;31#xff0c;33#xff0c;36#xff0c;34]#xff0c;那么输出为[3#xff0c;1#xff0c;1#xff0c;0#xff…题目
输入一个数组它的每个数字是某天的温度。请计算每天需要等几天才会出现更高的温度。例如如果输入数组[3531333634]那么输出为[31100]。由于第1天的温度是35℃要等3天才会出现更高的温度36℃因此对应的输出为3。第4天的温度是36℃后面没有更高的温度它对应的输出是0。其他的以此类推。
分析
用一个栈保存每天的温度在数组中的下标。每次从数组中读取一个温度然后将其与栈中保存的温度根据下标可以得到温度进行比较。如果当前温度比位于栈顶的温度高那么就能知道位于栈顶那一天需要等待几天才会出现更高的温度。然后出栈1次将当前温度与下一个位于栈顶的温度进行比较。如果栈中已经没有比当前温度低的温度则将当前温度在数组中的下标入栈。
解
public class Test {public static void main(String[] args) {int[] tokens {35, 31, 33, 36, 34};int[] result dailyTemperatures(tokens);for (int res : result) {System.out.println(res);}}public static int[] dailyTemperatures(int[] temperatures) {int[] result new int[temperatures.length];StackInteger stack new Stack();for (int i 0; i temperatures.length; i) {while (!stack.empty() temperatures[i] temperatures[stack.peek()]) {int prev stack.pop();result[prev] i - prev;}stack.push(i);}return result;}
}