使用C++找到数组中的正负值对

2023年 9月 21日 13.9k 0

使用C++找到数组中的正负值对

在本文中,我们有一个包含不同元素的数组。我们需要打印数组中具有相同绝对值的正负值对,并按排序顺序打印它们,例如 -

Input : arr[] = { 1, -1, 11, 12, 56, 77, -56, -12, -88}
Output : -1 1 -12 12 -56 56

Input : arr[] = {30, 40, 50, 77, -51, -50, -40}
Output : -40 40 -50 50

登录后复制

寻找解决方案的方法

我们首先想到的方法是蛮力法,然后我们还想出了一种称为高效法的方法。我们将讨论这两种方法。

蛮力法

在这种方法中,我们将用一个索引遍历数组,并找到相同的绝对值但不同的索引。

示例

#include
using namespace std;

int main() {
int arr[] = { 1, -1, 11, 12, 56, 77, -56, -12, -88 };
int n = sizeof(arr)/sizeof(int); // size of our array.
vector nums; // the present pairs.

for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
if(abs(arr[j]) == abs(arr[i])) { // finding the pairs.
nums.push_back(abs(arr[i]));
break;
// if we found the pair then we can just break as there are distinct elements in the array.
}
}
}
sort(nums.begin(), nums.end());
for(auto x : nums) // printing the pairs.
cout

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论