File tree Expand file tree Collapse file tree 1 file changed +23
-9
lines changed Expand file tree Collapse file tree 1 file changed +23
-9
lines changed Original file line number Diff line number Diff line change @@ -301,32 +301,46 @@ func dailyTemperatures(num []int) []int {
301301
302302JavaScript:
303303``` javascript
304- /**
305- * @param {number[]} temperatures
306- * @return {number[]}
307- */
304+ // 版本一
308305var dailyTemperatures = function (temperatures ) {
309- let n = temperatures .length ;
310- let res = new Array (n).fill (0 );
311- let stack = []; // 递减栈 :用于存储元素右面第一个比他大的元素下标
306+ const n = temperatures .length ;
307+ const res = Array (n).fill (0 );
308+ const stack = []; // 递增栈 :用于存储元素右面第一个比他大的元素下标
312309 stack .push (0 );
313310 for (let i = 1 ; i < n; i++ ) {
314311 // 栈顶元素
315- let top = stack[stack .length - 1 ];
312+ const top = stack[stack .length - 1 ];
316313 if (temperatures[i] < temperatures[top]) {
317314 stack .push (i);
318315 } else if (temperatures[i] === temperatures[top]) {
319316 stack .push (i);
320317 } else {
321318 while (stack .length && temperatures[i] > temperatures[stack[stack .length - 1 ]]) {
322- let top = stack .pop ();
319+ const top = stack .pop ();
323320 res[top] = i - top;
324321 }
325322 stack .push (i);
326323 }
327324 }
328325 return res;
329326};
327+
328+
329+ // 版本二
330+ var dailyTemperatures = function (temperatures ) {
331+ const n = temperatures .length ;
332+ const res = Array (n).fill (0 );
333+ const stack = []; // 递增栈:用于存储元素右面第一个比他大的元素下标
334+ stack .push (0 );
335+ for (let i = 1 ; i < n; i++ ) {
336+ while (stack .length && temperatures[i] > temperatures[stack[stack .length - 1 ]]) {
337+ const top = stack .pop ();
338+ res[top] = i - top;
339+ }
340+ stack .push (i);
341+ }
342+ return res;
343+ };
330344```
331345
332346
You can’t perform that action at this time.
0 commit comments