1. 程式人生 > 其它 >leetcode, LC64:最大的長方形

leetcode, LC64:最大的長方形

技術標籤:leetcode演算法leetcode資料結構

1 題目描述

給出一個只包含0和1的二維矩陣,找出最大的全部元素都是1的長方形區域,返回該區域的面積。

2 解題思路

https://blog.csdn.net/qq_41855420/article/details/87459549

3 程式碼實現

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        int n_rows = matrix.size();
        int n_cols =
matrix[0].size(); if(n_rows == 0 || n_cols == 0) return 0; vector<vector<int>> mat_trans(n_rows, vector<int>(n_cols)); // 1st map: char2int for(int i = 0; i < n_rows; i++) for(int j = 0; j < n_cols; j++) mat_trans[
i][j] = matrix[i][j] - '0'; // 2nd map: transform for(int i = 1; i < n_rows; i++) // note that i = 1 at first for(int j = 0; j < n_cols; j++) if(mat_trans[i][j] == 1) mat_trans[i][j] = mat_trans[i - 1][j] + 1; // bravo! // 3rd map: monostack
int max_area = 0; for(int i = 0; i < n_rows; i++){ max_area = max(max_area, largestRectangleArea(mat_trans[i])); } return max_area; } private: int largestRectangleArea(vector<int>& height) { // write code here int area = 0; stack<int> stk; height.push_back(0); for(int i = 0; i < height.size(); i++){ if(stk.empty() || height[i] >= stk.top()){ stk.push(height[i]); } else{ int count = 0; while(!stk.empty() && height[i] < stk.top()){ count++; area = max(area, count * stk.top()); stk.pop(); } while(count--){ stk.push(height[i]); } stk.push(height[i]); } } return area; } };

4 執行結果

執行時間:6ms
佔用記憶體:888k