用 C++ 打印包含元素正负值的所有对
在这个问题中,我们得到一个由唯一整数构成的数组。我们需要返回数组中存在的所有整数对(正整数和负整数)。
让我们来看一个例子,以便更好地理解这个问题:
Input: array = {1 , 4 , 7 , -1, 2, 5, -7}
Output: -11 -33解决这个问题的一个简单方法是使用两个循环来查找正负数对。但是,这种解决方案比较复杂,时间复杂度为 O(n²) ,其中 n 是数组的大小。
但是,我们需要找到一个更高效的方法来解决这个问题。为此,我们将首先对数组进行排序。然后在这个排序后的数组中,对于每个负整数,查找其相反数(正整数)。二分查找将是一个不错的选择。并打印找到的数对。
示例
让我们来看一下这种方法的代码示例:
#include <bits/stdc++.h>
using namespace std;
void positiveNegativePair(int arr[], int n) ;
int main(){
int arr[] = { 1, 4, 6 , 3, -1, -2, 5, -6, -5 , 8 };
int n = 10;
cout<<"Postive Negative pairs in the array are :\n";
positiveNegativePair(arr, n);
return 0;
}
void positiveNegativePair(int arr[], int n){
bool pair_exists = false;
sort(arr, arr + n);
for (int i = 0; i < n; i++) {
if (arr[i] < 0) {
if (binary_search(arr, arr + n, -arr[i])) {
cout<<arr[i]<<", "<<-arr[i]<<"\t";
pair_exists = true;
}
}
else
break;
}
if (!pair_exists)
cout << "No positive-negative pairs exist in the code";
}输出
数组中的正负数对:
-6, 6 -5, 5 -1, 1
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP