int len = heights.length; if (len == 0) { return 0; }
时间: 2024-02-15 20:40:55 浏览: 20
// Initialize variables
int maxArea = 0;
int left = 0;
int right = len - 1;
// Loop through the array using two pointers
while (left < right) {
// Calculate the area of the current rectangle
int area = Math.min(heights[left], heights[right]) * (right - left);
// Update max area if necessary
maxArea = Math.max(maxArea, area);
// Move the pointer that points to the smaller height
if (heights[left] < heights[right]) {
left++;
} else {
right--;
}
}
return maxArea;
相关问题
#include <iostream> #include <stack> #include <vector> using namespace std; int largestRectangleArea(vector<int>& heights) { stack<int> s; int maxArea = 0; int n = heights.size(); for (int i = 0; i <= n; i++) { while (!s.empty() && (i == n || heights[s.top()] >= heights[i])) { int height = heights[s.top()]; s.pop(); int width = s.empty() ? i : i - s.top() - 1; maxArea = max(maxArea, height * width); } s.push(i); } return maxArea; } int main() { vector<int> heights = {1, 1, 1, 1, 1, 1, 1, 1}; cout << largestRectangleArea(heights) << endl; return 0; }手动输入矩阵
抱歉,这段代码是计算给定柱状图中最大矩形面积的程序,并不需要手动输入矩阵。如果您想要编写手动输入矩阵的程序,可以参考以下示例代码:
```
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cout << "请输入矩阵的行数和列数: ";
cin >> n >> m;
vector<vector<int>> matrix(n, vector<int>(m));
cout << "请输入矩阵元素: " << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
cout << "您输入的矩阵是: " << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
通过该程序,您可以输入矩阵的行数和列数,并手动输入矩阵的元素,最终输出您输入的矩阵。
使用kotlin解答这个题目:2418. 按身高排序 提示 简单 83 相关企业 给你一个字符串数组 names ,和一个由 互不相同 的正整数组成的数组 heights 。两个数组的长度均为 n 。 对于每个下标 i,names[i] 和 heights[i] 表示第 i 个人的名字和身高。 请按身高 降序 顺序返回对应的名字数组 names 。 示例 1: 输入:names = ["Mary","John","Emma"], heights = [180,165,170] 输出:["Mary","Emma","John"] 解释:Mary 最高,接着是 Emma 和 John 。 示例 2: 输入:names = ["Alice","Bob","Bob"], heights = [155,185,150] 输出:["Bob","Alice","Bob"] 解释:第一个 Bob 最高,然后是 Alice 和第二个 Bob 。 提示: n == names.length == heights.length 1 <= n <= 103 1 <= names[i].length <= 20 1 <= heights[i] <= 105 names[i] 由大小写英文字母组成 heights 中的所有值互不相同
```kotlin
fun sortNamesByHeight(names: Array<String>, heights: IntArray): Array<String> {
val n = names.size
for (i in 0 until n - 1) {
for (j in i + 1 until n) {
if (heights[i] < heights[j]) {
// 如果 i 的身高比 j 的身高小,则交换 i 和 j 对应的元素
val tmpName = names[i]
val tmpHeight = heights[i]
names[i] = names[j]
heights[i] = heights[j]
names[j] = tmpName
heights[j] = tmpHeight
}
}
}
return names
}
// 测试代码
fun main() {
val names = arrayOf("Mary", "John", "Emma")
val heights = intArrayOf(180, 165, 170)
val sortedNames = sortNamesByHeight(names, heights)
println(sortedNames.contentToString()) // 输出 ["Mary", "Emma", "John"]
}
```