@@ -486,5 +486,95 @@ var largestRectangleArea = function(heights) {
486486 return maxArea;
487487};
488488```
489+ TypeScript:
490+
491+ > 双指针法(会超时):
492+
493+ ```typescript
494+ function largestRectangleArea (heights: number[ ] ): number {
495+ let resMax: number = 0;
496+ for (let i = 0, length = heights.length; i < length; i++) {
497+ // 左开右开
498+ let left: number = i - 1,
499+ right: number = i + 1;
500+ while (left >= 0 && heights[ left] >= heights[ i] ) {
501+ left--;
502+ }
503+ while (right < length && heights[ right] >= heights[ i] ) {
504+ right++;
505+ }
506+ resMax = Math.max(resMax, heights[ i] * (right - left - 1));
507+ }
508+ return resMax;
509+ };
510+ ```
511+
512+ > 动态规划预处理:
513+
514+ ```typescript
515+ function largestRectangleArea(heights: number[]): number {
516+ const length: number = heights.length;
517+ const leftHeightDp: number[] = [],
518+ rightHeightDp: number[] = [];
519+ leftHeightDp[0] = -1;
520+ rightHeightDp[length - 1] = length;
521+ for (let i = 1; i < length; i++) {
522+ let j = i - 1;
523+ while (j >= 0 && heights[i] <= heights[j]) {
524+ j = leftHeightDp[j];
525+ }
526+ leftHeightDp[i] = j;
527+ }
528+ for (let i = length - 2; i >= 0; i--) {
529+ let j = i + 1;
530+ while (j < length && heights[i] <= heights[j]) {
531+ j = rightHeightDp[j];
532+ }
533+ rightHeightDp[i] = j;
534+ }
535+ let resMax: number = 0;
536+ for (let i = 0; i < length; i++) {
537+ let area = heights[i] * (rightHeightDp[i] - leftHeightDp[i] - 1);
538+ resMax = Math.max(resMax, area);
539+ }
540+ return resMax;
541+ };
542+ ```
543+
544+ > 单调栈:
545+
546+ ``` typescript
547+ function largestRectangleArea(heights : number []): number {
548+ heights .push (0 );
549+ const length: number = heights .length ;
550+ // 栈底->栈顶:严格单调递增
551+ const stack: number [] = [];
552+ stack .push (0 );
553+ let resMax: number = 0 ;
554+ for (let i = 1 ; i < length ; i ++ ) {
555+ let top = stack [stack .length - 1 ];
556+ if (heights [top ] < heights [i ]) {
557+ stack .push (i );
558+ } else if (heights [top ] === heights [i ]) {
559+ stack .pop ();
560+ stack .push (i );
561+ } else {
562+ while (stack .length > 0 && heights [top ] > heights [i ]) {
563+ let mid = stack .pop ();
564+ let left = stack .length > 0 ? stack [stack .length - 1 ] : - 1 ;
565+ let w = i - left - 1 ;
566+ let h = heights [mid ];
567+ resMax = Math .max (resMax , w * h );
568+ top = stack [stack .length - 1 ];
569+ }
570+ stack .push (i );
571+ }
572+ }
573+ return resMax ;
574+ };
575+ ```
576+
577+
578+
489579-----------------------
490580<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments