c++ - 查找数组中的对数,使得数组中存在的这些对之间的所有元素都小于对本身
问题描述
我们有一个不同的正整数数组。我们必须找到数组中的对数,使得数组中这些对之间的所有元素都小于对元素本身。
例如,如果数组是 [7 3 2 1 4 6 5],那么输出将为 10,因为 (7,4) 、 (7,6) 、 (3,4) 、 (2,4) 之间的所有整数在数组中小于提到的对,并且考虑到它们之间没有元素的 6 个相邻对,即。(size(array) - 1),因此 4 + 6 = 10。类似地,对于 [10 3 4 8 6],输出为 6,对于 [2 80 4 32],输出为 4。
我能够使用效率不高的蛮力方法(2个嵌套循环)以及使用具有O(N)(时间和空间)中的下一个/上一个更大元素的概念的堆栈来实现结果。然而,我正在寻找一种更有效或更快的方法(可能只是使用指针,或事先操作数组)而不使用任何额外的 DS/空间,即 O(N) 时间和 O(1) 空间。
我使用堆栈方法附加了我的代码:
#include <iostream>
#include <stack>
using namespace std;
int main(){
int n, pairs = 0;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
stack <int> s1, s2;
int i = 1;
s1.push(arr[0]);
while (i < n) {
if (!s1.empty() and arr[i] > s1.top()) {
s1.pop();
pairs++;
}
else {
s1.push(arr[i]);
i++;
}
}
int j = n - 2;
s2.push(arr[n-1]);
while(j > -1) {
if(!s2.empty() and arr[j] > s2.top()) {
s2.pop();
pairs++;
}
else {
s2.push(arr[j]);
j--;
}
}
cout << pairs;
}
解决方案
推荐阅读
- r - 基于 ID 列向数据框添加值列的更简单的 R 代码
- html - Bootstrap 4 响应式图像(imag-fluid)的问题
- javascript - 密码中未包含所有用户输入条件的问题
- ios - 在 SwiftUI 中创建底部主视图栏
- c# - 为什么当我在 Revit 上关闭 Windows 窗体插件中的子表单时,它会关闭整个插件?
- arrays - 如何创建指向多维数组的指针?
- java - 如何以编程方式将边距中的 px 转换为 dp?
- java - 使用 java bufferedReader 和 Scanner 解析文本文件
- linux - Ansible:检查文件文本,如果没有,添加它
- java - 如果第一个字符是负号,则字符串拆分,然后将其视为负号