LeetCode739

it2023-08-03  71

传送门: https://leetcode-cn.com/problems/daily-temperatures/ 这道题的话,首先想到的就是暴力解法,暴力出来还能过,不过效率是十分的低下的,先来看看暴力的代码,执行效果就像下面的一样 执行结果: 通过 显示详情 执行用时:1316 ms, 在所有 Java 提交中击败了5.01% 的用户 内存消耗:46.1 MB, 在所有 Java 提交中击败了75.40% 的用户

class Solution { public int[] dailyTemperatures(int[] T) { int[] res = new int[T.length]; for (int i = 0; i < T.length - 1; i++) { for (int j = i + 1; j < T.length; j++) { if (T[j] > T[i]) { res[i] = j - i; break; } } } return res; } }

再来就是根据栈的特性来解答,效率高了那么一丢丢,不过还是可以的了 执行结果: 通过 显示详情 执行用时:20 ms, 在所有 Java 提交中击败了67.35% 的用户 内存消耗:46.4 MB, 在所有 Java 提交中击败了61.10% 的用户

class Solution { public int[] dailyTemperatures(int[] T) { Stack<Integer> stack = new Stack<>(); //开辟数组来储存下标的差 int[] res = new int[T.length]; //遍历数组 for(int i = 0; i < T.length; ++i){ //栈不为空并且T[i]>栈顶元素 while(!stack.isEmpty() && T[i] > T[stack.peek()]){ int temp = stack.pop(); res[temp] = i - temp; } stack.push(i); } return res; } }
最新回复(0)