[算法]CSDN编程挑战赛之寻找直方图中面积最大的矩形

简介: 继续看挑战赛的算法,虽然不指望能得到什么奖项,但能够将自己的思想用程序表达出来就是一种乐趣! 请看题: 我的解题思路: 就是判断[i,i+1,i+2...j]之间的最小高度H,然后通过s=(j-i+1)*H来计算面积,然后筛选出最大的面积。

继续看挑战赛的算法,虽然不指望能得到什么奖项,但能够将自己的思想用程序表达出来就是一种乐趣!

请看题:


我的解题思路:

就是判断[i,i+1,i+2...j]之间的最小高度H,然后通过s=(j-i+1)*H来计算面积,然后筛选出最大的面积。

C++代码:

//寻找直方图中面积最大的矩形
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;


//返回一段区间中最矮的那个索引
int short(vector<int> arr,int start,int end)  
{  


int short=arr[start];  
int index=start;  
int i;  
if(start==end)  
{  
return index;   
}  




for(i=start;i<=end;i++)  
{     
if(short>=arr[i])  
{  
short=arr[i];  
index=i;  
}  
}  
return index;  
}


int largestRectangleArea(vector<int> &height) {
int area = 0;
int max = 0;
int height_index=0;
for (int i=0;i<height.size();i++)
{
for (int j=i;j<height.size();j++)
{
height_index=shortest(height,i,j);  
area=(j-i+1)*(height[height_index]);  
if(max < area)  
max=area;  
}
}
return max;
}



关于C++泛型的一些东西,可以去看我博客中的这部分内容:http://blog.csdn.net/dingxiaowei2013/article/details/9814495



C++具有模板还稍微好一点,如果用C写可以用指针来写


C语言代码:

#include <stdio.h>

//找出区间最小值的索引
int shortindex(const int * height,int begin,int end)
{
	int shortindex;
	int shortheight=*height;
	if (begin=end)
	{
		return begin;
	}
	else
	{
		for (int i=begin;i<end;i++,height++)
		{
			if (shortheight>*height)
			{
				shortheight=*height;
				shortindex=i;
			}
		}
		return shortindex;
	}
	
}

//数组指针,数组个数
int largestRectangleArea(const int *height,int n)
{
	int area = 0;
	int max = 0;
	int height_index = 0;
	for (int i=0;i<n;i++)
	{
		for (int j=i;j<n;j++)
		{
			height_index=shortindex(height,i,j);
			area = (j-i+1)*(height[height_index]);
			if (max<area)
			{
				max=area;
			}
		}
	}
	return max;
}


==================== 迂者 丁小未 CSDN博客专栏=================

MyBlog:http://blog.csdn.net/dingxiaowei2013             MyQQ:1213250243

Unity QQ群:858550         cocos2dx QQ群:280818155

====================== 相互学习,共同进步 ===================

转载请注明出处:http://blog.csdn.net/dingxiaowei2013/article/details/17472397

欢迎关注我的微博: http://weibo.com/u/2590571922
相关文章
|
12月前
|
Serverless C语言 C++
【数学建模】利用C语言来实现 太阳赤纬 太阳高度角 太阳方位角 计算和求解分析 树木树冠阴影面积与种植间距的编程计算分析研究
【数学建模】利用C语言来实现 太阳赤纬 太阳高度角 太阳方位角 计算和求解分析 树木树冠阴影面积与种植间距的编程计算分析研究
197 1
牛客竞赛21842 正方形检测
牛客竞赛21842 正方形检测
|
5月前
|
算法
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
43 3
|
5月前
|
图形学
【计算机图形学】期末复习Bezier曲线与曲面篇
【计算机图形学】期末复习Bezier曲线与曲面篇
|
JavaScript 前端开发
第十三届蓝桥杯真题之灯的颜色变化
第十三届蓝桥杯真题之灯的颜色变化
119 0
|
算法
算法创作|纸牌三角形
算法创作|纸牌三角形
64 0
|
算法 图形学
【计算机图形学】期末复习part1:直线与曲线的绘制
【计算机图形学】期末复习part1:直线与曲线的绘制
160 0
【计算机图形学】期末复习part1:直线与曲线的绘制
LeetCode每日一题(10)——三维形体投影面积(保姆级)
三维形体投影面积 1.题目 2.示例 3.思路 理解题目 解题思路 4.代码
114 0
LeetCode每日一题(10)——三维形体投影面积(保姆级)
|
Python
LeetCode每日一题——883. 三维形体投影面积
在 n x n 的网格 grid 中,我们放置了一些与 x,y,z 三轴对齐的 1 x 1 x 1 立方体。
117 0
LeetCode每日一题——883. 三维形体投影面积
下一篇
无影云桌面