数据结构9
2016-07-17 23:44
281 查看
程序员代码面试指南(左程云)读书笔记(9)
第一章
求最大子矩阵的大小
题目:
给定一个整型矩阵map,其中的值只有0和1两种,求其中全是1的所有矩形区域中最大的矩形区域为1的数量。
例如:
1 1 1 0
其中,最大的矩形区域有3个1,所以返回3.
再如:
1 0 1 1
1 1 1 1
1 1 1 0
其中,最大的矩形区域有6个1,所以返回6.
解:
package com.nine;
import java.util.Stack;
public class Nine {
public static void main(String[] args) {
}
public int maxRecSize(int[][] map){
if(map==null||map.length==0||map[0].length==0){
return 0;
}
int maxArea=0;
int[] height=new int[map[0].length];
for(int i=0;i<map.length;i++){
for(int j=0;j<map[0].length;j++){
height[j]=map[i][j]==0?0:height[j]+1;
}
maxArea=Math.max(maxRecFromBottom(height), maxArea);
}
return maxArea;
}
public int maxRecFromBottom(int[] height){
if(height==null||height.length==0){
return 0;
}
int maxArea=0;
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<height.length;i++){
while(!stack.isEmpty()&& height[i]<=height[stack.peek()]){
int j=stack.pop();
int k=stack.isEmpty()?-1:stack.peek();
int curArea=(i-k-1)*height[j];
maxArea=Math.max(maxArea, curArea);
}
stack.push(i);
}
while(!stack.isEmpty()){
int j=stack.pop();
int k=stack.isEmpty()?-1:stack.peek();
int curArea=(height.length-k-1)*height[j];
maxArea=Math.max(maxArea, curArea);
}
return maxArea;
}
}
第一章
求最大子矩阵的大小
题目:
给定一个整型矩阵map,其中的值只有0和1两种,求其中全是1的所有矩形区域中最大的矩形区域为1的数量。
例如:
1 1 1 0
其中,最大的矩形区域有3个1,所以返回3.
再如:
1 0 1 1
1 1 1 1
1 1 1 0
其中,最大的矩形区域有6个1,所以返回6.
解:
package com.nine;
import java.util.Stack;
public class Nine {
public static void main(String[] args) {
}
public int maxRecSize(int[][] map){
if(map==null||map.length==0||map[0].length==0){
return 0;
}
int maxArea=0;
int[] height=new int[map[0].length];
for(int i=0;i<map.length;i++){
for(int j=0;j<map[0].length;j++){
height[j]=map[i][j]==0?0:height[j]+1;
}
maxArea=Math.max(maxRecFromBottom(height), maxArea);
}
return maxArea;
}
public int maxRecFromBottom(int[] height){
if(height==null||height.length==0){
return 0;
}
int maxArea=0;
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<height.length;i++){
while(!stack.isEmpty()&& height[i]<=height[stack.peek()]){
int j=stack.pop();
int k=stack.isEmpty()?-1:stack.peek();
int curArea=(i-k-1)*height[j];
maxArea=Math.max(maxArea, curArea);
}
stack.push(i);
}
while(!stack.isEmpty()){
int j=stack.pop();
int k=stack.isEmpty()?-1:stack.peek();
int curArea=(height.length-k-1)*height[j];
maxArea=Math.max(maxArea, curArea);
}
return maxArea;
}
}
相关文章推荐
- 数据结构 线性链表
- 数据结构二叉树的实现,前序、中序、后序遍历
- 数据结构(二)非线性结构之二叉树
- 数据结构知识点
- 数据结构实验之栈八:栈的基本操作
- 最大子序列和问题四种解(O)
- 【NOIP2016提高A组模拟7.15】颜料大乱斗
- 数据结构—栈
- bzoj1018 堵塞的交通traffic(线段树)
- 数据结构 顺序线性表
- 微软BI专题-海量数据处理分析 3ff8
- hdu 5367(线段树+区间合并)
- 《数据结构》2.2顺序表(sequence list)
- longest-valid-parentheses
- 数据结构(8) 构造数组的MaxTree
- 浙大PAT 4-09. 笛卡尔树 (解题思路)
- 1.1数据结构基本概念
- 复习(数据结构):链表:c++:标准
- 布隆过滤器 -- 空间效率很高的数据结构
- 浅谈树链剖分(每日不间断更新中)