739. Daily Temperatures - LeetCode
Posted okokabcd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了739. Daily Temperatures - LeetCode相关的知识,希望对你有一定的参考价值。
Question
Solution
题目大意:比今天温度还要高还需要几天
思路:笨方法实现,每次遍历未来几天,比今天温度高,就坐标减
Java实现:
public int[] dailyTemperatures(int[] temperatures) {
int[] ans = new int[temperatures.length];
for (int i = 0; i<temperatures.length; i++) {
int highIdx = i;
for (int j=i+1; j<temperatures.length; j++) {
if (temperatures[j] > temperatures[i]) {
highIdx = j;
break;
}
}
ans[i] = highIdx - i;
}
return ans;
}
Ref
别人实现高效的方法
https://leetcode.com/problems/daily-temperatures/discuss/109832/Java-Easy-AC-Solution-with-Stack
Stack
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int[] ret = new int[temperatures.length];
for(int i = 0; i < temperatures.length; i++) {
while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int idx = stack.pop();
ret[idx] = i - idx;
}
stack.push(i);
}
return ret;
}
Array
public int[] dailyTemperatures(int[] temperatures) {
int[] stack = new int[temperatures.length];
int top = -1;
int[] ret = new int[temperatures.length];
for(int i = 0; i < temperatures.length; i++) {
while(top > -1 && temperatures[i] > temperatures[stack[top]]) {
int idx = stack[top--];
ret[idx] = i - idx;
}
stack[++top] = i;
}
return ret;
}
以上是关于739. Daily Temperatures - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章
739. Daily Temperatures - LeetCode
[栈] leetcode 739 Daily Temperatures
LeetCode 739:每日温度 Daily Temperatures