标签:vector 高度 lines nta least 原来 就会 处理 ++
/* 原问题: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2. 解析:这是一道考察算法的题目,如果你没有get到那个点,就会搞得很复杂,但是简化了问题之后就会恍然大悟,非常的简单 简化的代码和原来的代码如下 */class Solution { public: int maxArea(vector<int>& height) { int left = 0; int right = height.size() - 1; int max = 0; while (right > left) { max = std::max(min(height[right], height[left]) * (right - left), max); if (height[right] > height[left]) left++; else right--; } return max; } };
struct structure { int height;// 表示高度 int sub;// 表示下标 structure(int height, int sub):height(height), sub(sub){} }; class Solution { public: int maxArea(vector<int>& height) { int max_height = *max_element(height.begin(), height.end()); // left容器存放从左往右递增的高度,到最高为止 // right容器存放从有往左递增的高度,到最高为止 vector<structure> left(1, structure(height[0], 0)); vector<structure> right(1, structure(height[height.size() - 1], height.size() - 1)); // 填充left容器 int index = 1; while (true) { if (left[left.size() - 1].height == max_height) break; if (height[index] > left[left.size()-1].height) left.insert(left.end(), structure(height[index], index)); index++; } // 填充right容器 index = height.size() - 2; while (true) { if (right[right.size() - 1].height == max_height) break; if (height[index] > right[right.size() - 1].height) right.insert(right.end(), structure(height[index], index)); index--; } // 不断将left、right容器的最小的高度pop出来计算该高度水位的面积,找出最大的面积 int max_area = 0; while (left.size() != 1 || right.size() != 1) { if (left[0].height < right[0].height) { int area = left[0].height * (right[0].sub - left[0].sub); if (area > max_area) max_area = area; left.erase(left.begin()); } else { int area = right[0].height * (right[0].sub - left[0].sub); if (area > max_area) max_area = area; right.erase(right.begin()); } } // 单独处理left、right容器各自剩下的最后一个max_height int area = left[0].height * (right[0].sub - left[0].sub); if (area > max_area) max_area = area; return max_area; } };
标签:vector 高度 lines nta least 原来 就会 处理 ++
原文地址:https://www.cnblogs.com/jkn1234/p/8969744.html